首页 > 解决方案 > 带有条件语句的 Laravel Eager Load

问题描述

今天是个好日子

我是 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
    ]);
}

这个怎么做?

更新

我找到了一种按点赞数排序评论的方法,但如果每条评论中都没有点赞,我不知道如何通过“created_at”(获取最新评论)对评论进行排序

我需要包含“likes_count” withCount('likes') ,然后按降序排列

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”(最新的)排序评论?

提前致谢

标签: laraveleloquentsql-order-bylaravel-relations

解决方案


您当前的方法看起来很适合按喜欢计数排序结果,如果没有喜欢,您仍然可以通过添加另一个带有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);

从最初的评论复制

因此,如果所有评论都有 0 个赞,那么最新的评论将首先出现在列表中,如果评论有赞,那么它们也将首先按赞数排序,然后按创建时间排序。

一旦您订购了集合,然后当您循环您的新闻记录时,然后从您的相关记录中选择第一项


推荐阅读