jeudi 17 mars 2016

Laravel - joining 2 tables with OR operator

I have a table called messages, and it's columns are

id, sender_id, message, receiver_id, created_at, updated_at

And the other table is called users, and it's columns are

id, firstname, lastname, email, password, created_at,updated_at

I want to get all the messages from all the users, so I'm joining the messages.sender_id and messages.receiver_id with users.id

However I don't know how to use "OR" operator while joining in laravel here's my raw query that gives me the desired output.

SELECT messages.*,users.* FROM messages JOIN users ON users.id = messages.sender_id 
OR users.id = messages.receiver_id GROUP BY messages.id

Here's the laravel query that I tried

$get_messages = DB::table('messages')
            ->where('messages.sender_id',$user_id)
            ->leftjoin('users', function($join){
                $join->on('users.id','=','messages.sender_id'); // i want to join the users table with either of these columns
                $join->on('users.id','=','messages.receiver_id');
            })
            ->orwhere('messages.sender_id',$partner_id)
            ->where('messages.receiver_id',$user_id)
            ->orwhere('messages.receiver_id',$partner_id)
            ->groupby('messages.id')
            ->get();

print_r($get_messages);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire