Laravel查询适合评论与关系

时间:2019-06-01 06:53:56

标签: mysql laravel eloquent

$listing = Listing::orderBy('created_at','DESC')->where('user_id', Auth::User()->id)
->with('reviews')
->with('posts')
->get();

尝试此操作时如何过滤审阅顺序

 ->whereHas('reviews', function ($query) {
            $query->where('status', 'Public');
        })->orderBy('created_at','DESC')

我想尝试在审阅中使用orderBy,但是当我在审阅中尝试使用orderBy时,它的筛选器也发布,但是我不想发布,因此请帮助!

2 个答案:

答案 0 :(得分:0)

尝试此查询:

$listing = Listing::where('user_id', Auth::User()->id)
->with(['reviews','posts'])
->whereHas('reviews', function ($query) {
        $query->where('status', 'Public')->orderBy('created_at','DESC');
    })
->orderBy('created_at','DESC')
->get();

答案 1 :(得分:0)

您可以在whereHas函数中应用更多过滤器,但是要应用更多条件(例如排序和限制),则应在with函数中对要加载的正确关系进行调用。

$listing = Listing::where('user_id', Auth::User()->id)
    ->with(['reviews' => function ($query) {
        return $query->orderByDesc('created_at');
    }, 'posts'])
    ->whereHas('reviews', function ($query) {
        return $query->where('status', 'Public');
    })
    ->orderByDesc('created_at')
    ->get();