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);
In Laravel, we can write the following code to represent the above full outer join: $second = DB::table('t2') ->rightJoin('t1', 't1.id', '=', 't2.id') $first = DB::table('t1') ->leftJoin('t2', 't1.id', '=', 't2.id') ->unionAll($first) ->get();
The Laravel Right JOIN clause returns all rows from the right table, even if there are no matches in the left table, The result is NULL from the left side.
Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.
laravel eloquent Join method by default use inner join. For example if you have 10 rows and you want the join from other table then it will only return the rows which satisfy both the tables. Laravel eloquent or query builder join method do the same as MySQL inner join function.
Try this.
->leftjoin('users', function($join){
$join->on('users.id','=','messages.sender_id'); // i want to join the users table with either of these columns
$join->orOn('users.id','=','messages.receiver_id');
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With