Php Laravel原始查询生成器:按datetime列的条件max()选择id
我这里有个问题。我必须获得这些频道,并且在这些频道中有字段content\u id和开始\u时的内容属于这个频道 因此,问题是我可以获取Php Laravel原始查询生成器:按datetime列的条件max()选择id,php,laravel-5,Php,Laravel 5,我这里有个问题。我必须获得这些频道,并且在这些频道中有字段content\u id和开始\u时的内容属于这个频道 因此,问题是我可以获取max(开始于)但我无法获取内容id。如何通过selectRaw()中的max(开始于)获取内容id 我的问题是: $channels = \DB::table('channels') ->selectRaw(' channels.*, max(contents.be
max(开始于)
但我无法获取内容id。如何通过selectRaw()中的max(开始于)
获取内容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();
由于在查询中创建了
latest\u message\u time
字段,因此不能立即使用->orderByDesc('latest\u message\u time')
。而不是orderByDesc
使用orderByRaw(“max(contents.start_at)DESC”)
max()
将返回所提供的列。可能是select content\u id order by start\u at desc
谢谢,它不起作用。当这样选择时,我需要按内容\u id分组,但我必须获得一个内容\u id(最新的内容\u id,开始时间为max)。谢谢您的评论,没关系,我的代码运行良好:D,它可以orderByDesc(“最新消息\u时间”)。但是我可以获取与max相对应的content\u id('contents.start\u at')。