php - 多个动态查询范围

标签 php laravel

我已经在我的数据库查询上构建了一个过滤器,现在 我想让它更舒适。 目标是让它变得动态,这意味着 用户可以选择任意组合。

public function filter(FilterList $request)
{
    $view = view('profile.browse.list');
    $search = $request->get('filter');

    $filter = [
            'male'   => Profile::male(),
            'female' => Profile::female(),
            '10'     => Profile::man(),
            '11'     => Profile::women(),
            '12'     => Profile::couple(),
            '15'     => Profile::domina(),
            '20'     => Profile::affaire(),
            '21'     => Profile::cybersex(),
            '22'     => Profile::marriage(),
            '23'     => Profile::flirt(),
    ];

    return $view->with([
        'List' => $filter[$search]->unmoderated()->paginate(15)->appends(['filter' => $search]),
    ]);

}

我知道我的解决方案并不是一个很好的解决方案。 我已将查询范围保存在 $filter 数组中,并且 不能像这样添加第二个或第三个范围

$users = User::popular()->women()->orderBy('created_at')->get();

http://laravel.com/docs/5.0/eloquent#query-scopes

有任何提示可以让我做得更好。

我不知道要开始...

感谢您的帮助

编辑

public function scopeMarriage($query)
{
 return $query->where('LookFor', 'LIKE', '%Ehe%');
}

最佳答案

因此,用户正在提交动态数量的输入,并且基于这些输入,您想将查询范围链接到您的查询吗?如果那是你想要的,我相信你可以这样做:

// Method array taken from your example
$methods = [
    'male'    => 'male',
    'female'  => 'female',
    '12'      => 'couple',
];

// Begin the query. Since the unmoderated() scope query is always called,
// I used that in this example.
// But note that you can also use Model::query(); to begin a query
$query = Profile::unmoderated();

// Loop through the request inputs
foreach ($request->all() as $param)
{
    // If it exists in the provided array, add it to the query.
    if (array_key_exists($param, $methods))
    {
        $query->{$methods[$param]}();
    }
}

// Call get, paginate, etc. to actually fetch the results and then return it.
return $query->paginate(15);

关于php - 多个动态查询范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33367128/

相关文章:

如果授权失败,Laravel 自定义错误页面

mysql - 如何从多对多关系的两个表中获取数据?

php - MySQL OUTER JOIN 从连接表中获取单独的行结果

php - 在 PHP 中获取复杂数组的索引

php - 哪个更符合逻辑且性能更好?一个 CI 应用程序或多个 CI 应用程序

php - 在 Laravel 中上传小文件但不是大文件

php - PHP 检测文件是否完整或部分

PHP 在构造函数中访问属性

php - 为什么在创建新项目时会出现 Laravel 错误?

laravel - 在laravel eloquent中一次插入多条记录