问题描述
有两个表格视频和反应。
我想按喜欢程度降序对视频进行排序。
反应表对于喜欢和不喜欢是相同的。 (我不想为喜欢和不喜欢创建两个不同的表)。
反应表中有反应列,其中reaction = 1
表示喜欢,reaction = 2
表示不喜欢强>
问题是我的代码没有 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);
解决方法
非常感谢 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);