doutun9179 2015-10-27 11:43
浏览 140
已采纳

多个动态查询范围

I have build a filter on my database query and now I want to make it more comfortable. The goal is to make it dynamic that mean's the user has the option to combine as many as he wants.

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]),
    ]);

}

I know that my solution is not really a good solution. I have saved the query scopes in the $filter array and can not add a a second or thired scope like this

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

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

Have anyony hint's for me for making it better.

I have no idea to start ...

Thanks for any help

Edit

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

1条回答 默认 最新

  • doubu1964 2015-10-28 20:28
    关注

    So, the user is submitting a dynamic number of inputs, and based on those inputs, you want to keep chaining query scopes onto your query? If that's what you want, I believe you can do something like this this:

    // 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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行