簡體   English   中英

過濾器組合可選 laravel eloquent 關系

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

我想根據傳遞的查詢參數過濾回復,查詢參數可以是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']);
        });
    }

現在,如果我想再次使用comment authors進行過濾,即在評論表上,如果我想添加post author的過濾器,那將在帖子表上,我如何添加這些條件,並且仍然是可選的?

只需在下面添加另一個 if 語句。 這些將是可選的,因為您在第一次過濾操作之前定義了$query

我需要使用另一個急切加載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