Laravel 查询不想 select 最后一个

Laravel query doesn't want to select last one

我之前尝试过 distinct,但不知何故我的查询不会 select 最后一条评论。他总是 select 最早的评论。然后我尝试使用 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();

它很长。 希望有人能向我解释为什么这行不通。

尝试使用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();

要做到这一点,必须要有函数建立的关系,比如Comment模型中的topics(即:hasMany)

目前发现的错误

  1. 不需要groupBy
  2. 您的连接语句 join('topics', 'comments.topic_id', '=', 'comments.id') 应该连接 table 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();