![](/img/trans.png)
[英]Laravel Query builder select same table same column with diferent condition
[英]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.