大家。我已经编写了这段代码,它应该返回在指定日期之后发布的最喜欢的视频。但是代码返回比指定日期更早的结果。我在2020.07.26之后只发布了一个视频,尽管如此,Eloquent 还是返回了 8 个较旧的视频。
$query = Video::select('videos.id',DB::raw('group_concat(DISTINCT videos.code) AS code'),DB::raw('group_concat(DISTINCT videos.title) AS title'),DB::raw('group_concat(DISTINCT videos.created_at) AS createdDate'),DB::raw('count(reactions.id) AS reactCount'))
->leftJoin('reactions','reactions.at_video','=','videos.id')
->where('reactions.reaction',1)
->orWhereNull('reactions.reaction')
->where('videos.created_at', '>', '2020.07.26 14:16:29')
->groupBy('videos.id')
->orderBy('reactCount','DESC')
->get();
dd($query);
然后我在解决方案所在的 stockflow 上找到了这段代码whereColumn
。但这对我没有帮助。Laravel 向我展示了另一个错误。
stackoverflow 上另一篇文章中的whereColumn示例
$query = DB::table('messages')
->leftJoin('participants', function ($join) {
$join->on('messages.thread_id', '=', 'participants.thread_id')
->on('messages.user_id', '!=', 'participants.user_id');
})
->select('messages.created_at as message_date', 'participants.last_read as last_read')
->whereColumn('messages.created_at', '>', 'participants.last_read')->get();
这样做的原因是我对结果进行了分组。该videos.created
字段返回值的次数与视频的次数一样多。为了解决这个问题,我使用了DISTINCT
DB::raw('group_concat(DISTINCT videos.created_at) AS createdDate')
然后我添加createdDate
了WHERE()
,不幸的是我又遇到了另一个错误。
->where('createdDate', '>', '2020.07.26 14:16:29')
这就是我的意思的错误。很多次我得到它......我几乎喜欢它;)
而且... 我编写了一个查询代码,它返回正确的结果并在本机 php 页面中运行。 这是 Laravel 应该做的,但它没有......
SELECT videos.id AS id, group_concat(videos.code) AS code, group_concat(videos.title) AS title, group_concat(DISTINCT videos.created_at) AS createdDate, count(reactions.id) AS reactCount
FROM videos
LEFT JOIN reactions ON videos.id = reactions.at_video
WHERE (reactions.reaction = 1 or reactions.reaction IS NULL)
AND videos.created_at > '2020.07.27'
GROUP BY videos.id
ORDER BY reactCount DESC
我以为我会在 Laravel 中使用自定义查询代码作为最终解决方案,但我不得不再说一遍。
$videos = DB::select("SELECT videos.id AS id, group_concat(videos.code) AS code, group_concat(videos.title) AS title, group_concat(DISTINCT videos.created_at) AS createdDate, count(reactions.id) AS reactCount
FROM videos
LEFT JOIN reactions ON videos.id = reactions.at_video
WHERE (reactions.reaction = 1 or reactions.reaction IS NULL)
AND videos.created_at > '2020.07.27'
GROUP BY videos.id
ORDER BY reactCount DESC")->paginate(16);
请有人帮我找到解决方案。我真的很累人。