Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 722
KennethC Avatar asked Mar 18 '16 02:03

KennethC


People also ask

How use outer join in laravel?

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

What is the use of join in laravel?

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.

What is laravel query builder?

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.

How do I join eloquent?

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.


1 Answers

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');
            })
like image 182
aadarshsg Avatar answered Oct 07 '22 00:10

aadarshsg