dimanche 17 novembre 2019

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

everybody. I have a problem here. I have to get the channels, and in these channels have field content_id and began_at time of the content belong to this channel. So the matter here is I can get max(began_at) but I can not get the content_id. How can I get the content_id by max(began_at) in selectRaw()?

My query:

 $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();
    ```

Thank you very much! 


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire