繁体   English   中英

Laravel 原始查询生成器:select id 按日期时间列的条件 max()

[英]Laravel Raw Query Builder: select id by condition max() at datetime column

我这里有问题。 我必须得到频道,并且在这些频道中有字段 content_id 和 begin_at 时间的内容属于这个频道。

所以问题是我可以获得max(began_at)但我无法获得 content_id。 如何在 selectRaw() 中通过max(began_at)获取 content_id?

我的查询:

 $channels = \DB::table('channels')
            ->selectRaw('
                channels.*,
                max(contents.began_at) as latest_message_time
                ')
            ->join('subscriptions', static function (JoinClause $join) use ($device_id) {
                $join->on('subscriptions.channel_id', '=', 'channels.channel_id')
                    ->where('device_id', $device_id);
            })
            ->join('contents', static function (JoinClause $join) {
                $join->on('contents.channel_id', '=', 'subscriptions.channel_id');
            })
            ->join('content_user', static function (JoinClause $join) {
                $join->on('contents.content_id', '=', 'content_user.content_id');
                $join->on('subscriptions.user_id', '=', 'content_user.user_id');
            })
            ->orderByDesc('latest_message_time')
            ->groupBy('channels.channel_id')
            ->get();

您不能立即使用->orderByDesc('latest_message_time') ,因为在查询中创建了latest_message_time字段。 而不是orderByDesc

使用->orderByRaw("max(contents.began_at) DESC")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM