【问题标题】:Laravel query doesn't want to select last oneLaravel 查询不想选择最后一个
【发布时间】:2017-07-25 18:37:25
【问题描述】:

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

很长。 希望有人能解释一下为什么这不起作用。

【问题讨论】:

  • 你想达到什么目的?
  • @avonnadozie sorry die nu bad explaination 我想根据最后的 cmets 选择 5 个主题。
  • 等一下,我想选择最后一个主题未被删除且位于所选类别中的 cmets
  • 更新您的问题以显示这些
  • 您说您想要 cmets,但您正在选择主题。我猜你想要 5 个最新的主题以及最新评论的 user_id。请准确说明您想要什么。

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


【解决方案1】:

目前发现的错误

  1. 不需要groupBy
  2. 您的连接语句join('topics', 'comments.topic_id', '=', 'comments.id') 应该是连接表commentstopics 中的列

修复

\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 个主题中,也会给出每个最新评论。它还需要在 cmets.topic_id 上进行过滤
  • 如果您希望每个主题只返回一条评论,请按topics.id分组
  • 那么问题又来了,那时我得到的是最旧的评论而不是最新的评论。
  • 您尝试过解决方案吗?通过topics.id 而不是comments.id 修复连接和分组后,输出应该会改变
  • 我认为这个趋势有你想要的MySQL order by before group by
【解决方案2】:

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

【讨论】:

  • 调用未定义的方法 Illuminate\Database\Query\Builder::topics() 关系 commet 有一个属于 topic 并且 topic 有一个 hasmany cmets
  • 如果评论属于主题,请尝试whereHas('topic', function($q) {
  • whereIn('topics.cat_id', $cats) topics.cat_id 不存在;因为 join 不存在;如果我将 whereIn 添加到 $q 中,则无法访问变量 $猫?
  • 我已经编辑了答案,您必须使用use ($cats) 使其在函数中可用。请再试一次
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 2011-10-20
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
相关资源
最近更新 更多