Laravel查询不想选择最后一个

时间:2017-07-25 18:37:26

标签: php mysql laravel eloquent laravel-query-builder

之前我试过了不同的但不知何故我的查询没有选择最后的评论。他总是选择最古老的评论。然后我尝试使用groupBy而不是distinct。但这也不会奏效。

我当前的查询:

\App\Comment::limit(5)->groupBy('comments.id')
            ->orderBy('comments.id', 'desc')
            ->join('topics', 'comments.topic_id', '=', 'comments.id')
            ->select('comments.user_id', 'topics.id', 'topics.name')
            ->whereIn('topics.cat_id', $cats)
            ->where([['comments.removed', '=', false],['topics.removed', '=', false]])
            ->get();

很长。 有人可以解释一下为什么这不起作用。

2 个答案:

答案 0 :(得分:1)

到目前为止发现的错误

  1. 不需要groupBy
  2. 您的加入声明join('topics', 'comments.topic_id', '=', 'comments.id')应该加入表格commentstopics
  3. 中的列

    修复

    \App\Comment::select('comments.user_id', 'topics.id', 'topics.name')
        ->join('topics', 'comments.topic_id', 'topics.id')
        ->whereIn('topics.cat_id', $cats)
        ->where('comments.removed', false)
        ->where('topics.removed', false)
        ->latest('comments.id')
        ->limit(5)
        ->get();
    

    PS:latest('comments.id')对于orderBy('comments.id', 'desc')

    非常方便

    <强>更新

    要获取最多5个最近更新的主题的最新评论,请尝试此

    \App\Comment::select('comments.user_id', 'topics.id', 'topics.name')
        ->from(DB::raw("(select * from comments where removed = 0 order by id desc) as comments"))
        ->join('topics', 'comments.topic_id', 'topics.id')
        ->whereIn('topics.cat_id', $cats)
        ->where('topics.removed', false)
        ->groupBy('topics.id')
        ->limit(5)
        ->get();
    

答案 1 :(得分:0)

尝试使用whereHas。你应该这样做:

\App\Comment::where('removed', false)
            ->whereHas('topic', function($q) use ($cats) {
                $q->where('removed', false)
                  ->whereIn('cat_id', $cats);
            })
            ->limit(5)
            ->orderBy('id', 'desc')->get();

要实现这一点,您必须具有由topics模型中的Comment(即:hasMany)等函数建立的关系。