dimanche 11 novembre 2018

Laravel eloquent, how do i group by for 2 columns in relation

I have a messages table that looks like this:

  • id

  • user_id

  • target_user_id

  • message

What i would like to do is group up these by conversation.

So some typical records can look like this:

#1
user_id = 5
target_user_id = 10
message = hello
#2
user_id = 10
target_user_id = 5
message = hello
#3
user_id = 15
target_user_id = 20
message = hello
#2
user_id = 15
target_user_id = 20
message = hello

What i would like to achieve is how i can group all my records together so that all messages between user 5 and 10 for example is in a group and 15 and 20 is in a group and sorted by latest.

This is my current attempt:

$msgs = Message::with('user')
     ->where(function($q) {
     $q->where('user_id', Auth::user()->id)
        ->orWhere('target_user_id', Auth::user()->id);
     })
     ->groupBy('user_id', 'target_user_id')
            ->get();



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire