【问题标题】:Select all from first table and order by Count(id) from second table where second.value = 1从第一个表中选择全部并从第二个表中按 Count(id) 排序,其中 second.value = 1
【发布时间】:2021-10-03 03:41:44
【问题描述】:

有两个表格视频反应

我想按喜欢的降序对视频进行排序。 reactions 表对于喜欢和不喜欢是相同的。 (我不想为喜欢和不喜欢创建两个不同的表)。 reactions 表中有 reaction 列,其中reaction = 1 表示likesreaction = 2 表示disslikes

问题是我没有where('reactions.reaction', 1) 的代码返回按总反应(likes + disslikes) 排序的所有视频,而我只需要按likes 排序。

如果添加 where('reactions.reaction', 1) 那么我的查询将只返回带有赞的视频而不是所有视频。

我想从按喜欢排序的表格中获取所有视频,而不仅仅是喜欢的视频。 我该怎么办?

$videos = Video::select('videos.id', DB::raw('count(reactions.id) as total'))
->leftJoin('reactions', 'reactions.at_video', '=', 'videos.id')
// ->where('reactions.reaction', 1) // I need this for only reactions
->groupBy('videos.id')
->orderBy('total', 'DESC')
->get();

dd($videos);

【问题讨论】:

  • 我认为您应该使用联接而不是左联接,因此如果视频没有任何反应,则查询不会选择它们。
  • LEFT JOIN 是正确的方式,因为我们可以看到 LEFT JOIN 关键字返回左表(table1)中的所有记录,以及右表(table2)中的匹配记录。 w3schools.com/sql/sql_join_left.asp
  • 好吧,这对你有帮助 ->where(function ($q){ $q->where('reactions.reaction', 1)->orWhereNull(''reactions.reaction'); })
  • 谢谢伙计。你救了我。

标签: mysql laravel pdo eloquent table-relationships


【解决方案1】:

非常感谢 fake97 的解决方案。

我需要更改->where('reactions.reaction', 1)>where(function ($q){ $q->where('reactions.reaction', 1)->orWhereNull(''reactions.reaction');})

查看下面的代码

$videos = Video::select('videos.id', DB::raw('count(reactions.id) as total'))
->leftJoin('reactions', 'reactions.at_video', '=', 'videos.id')
->where(function ($q){ 
  $q->where('reactions.reaction', 1)->orWhereNull('reactions.reaction');
})
->groupBy('videos.id')
->orderBy('total', 'DESC')
->get();
      
dd($videos);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    相关资源
    最近更新 更多