Laravel 带有条件语句的预加载

Laravel Eager Load with conditional statement

大家好

我是 Laravel 的新手,目前正在使用它构建我的第一个简单新闻应用程序

我有一个简单的查询,使用 laravel 的预先加载功能 但是在这个预加载函数中,我想根据某些条件获取某些评论

示例:

use App\News;
...

public function home() {
    $news = News::with([
                    'thumbnail',
                    'source', // link to real news source
                    'comments' => function ($query) {
                        // fetch a comment where likes > 0, otherwise, get latest comment
                        // *get only one*
                    }
                ])->paginate(5);

    return response()->json([
        'news' => $news
    ]);
}

如何操作?

UPDATE

我找到了一种按赞数排序评论的方法,但我不知道如何按 'created_at'(获取最新评论)排序,如果每个评论中都没有点赞的话

我需要使用 withCount('likes') 包含 'likes_count' 然后按降序排列

public function home() {
    $news = News::with([
        'thumbnail',
        'source',
        'comments' => function ($query) {
            $query->withCount('likes');
            $query->orderBy('likes_count', 'DESC')->first();

            // return the first comment that has likes or most liked comment
        }
    ])->paginate(5);

    ...
}

如果评论中没有点赞,现在如何将回退查询按 'created_at'(最新的)对评论进行排序?

提前致谢

您当前的方法看起来很适合按点赞数对结果进行排序,如果没有点赞,您仍然可以通过在 created_at

中添加另一个 order by 子句来获取最新记录
$news = News::with([
    'thumbnail',
    'source',
    'comments' => function ($query) {
        $query->withCount('likes');
        $query->orderBy('likes_count', 'DESC')
              ->orderBy('created_at', 'DESC');
    }
])->paginate(5);

从最初的评论中复制

So if all comments have 0 likes then the newest one will appear first in list, same if comments have likes then they are also sorted first with likes count and then with created at.

一旦你订购了 collection 然后当你循环你的新闻记录时然后从你的相关记录中选择第一个项目