简体   繁体   English

过滤器组合可选 laravel eloquent 关系

[英]Combinations of filters can be optional laravel eloquent relationships

I want to filter replies based on query parameter passed, query parameters can be post_id, comment_id and array of reply_ids all can be optional and can be used as combination我想根据传递的查询参数过滤回复,查询参数可以是post_id,comment_id和reply_ids数组都可以是可选的,可以作为组合使用

 $query = Post::where('user_id', auth()->id());
    if ( isset($data['reply_ids']) ) {
        $query = $query->with('posts.comments.replies')->whereHas('posts.comments.replies', function($query) use ($data){
            $query->whereIn('id', $data['reply_ids']);
        });
    }

Now, if I want to filter again with comment authors , that is on comments table, if I want to add filters of post author , that will be on posts table, how I can add those conditional, and still that will be optional?现在,如果我想再次使用comment authors进行过滤,即在评论表上,如果我想添加post author的过滤器,那将在帖子表上,我如何添加这些条件,并且仍然是可选的?

Just add another if statements below.只需在下面添加另一个 if 语句。 Those will be optional, sice you define your $query before your first filtering action.这些将是可选的,因为您在第一次过滤操作之前定义了$query

I needed to use another eager loading with so that the query will be build on all the combination selected, so the final code will be something like我需要使用另一个急切加载with以便查询将建立在所有选择的组合上,因此最终代码将类似于

$query = Post::where('user_id', auth()->id());
if ( isset($data['reply_ids']) ) {
    $query = $query->with('posts.comments.replies')->whereHas('posts.comments.replies', function($query) use ($data){
        $query->whereIn('id', $data['reply_ids']);
    });
}
$query = $query->with(['posts' => function($query){ $query->where('status', 'pending'); }])

$query->get()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM