SoFunction
Updated on 2025-03-06

Detailed explanation of the advanced Join syntax of laravel and the use of Join multiple conditions

In laravel, we often use join, leftjion and rightjoin for table query, which is very convenient, but today I encountered a problem, that is, the linked list query requires multiple conditions, that is, the id of the order and the shipper I want are the same. The default join only supports a single query.So I will summarize two methods below:

1. Used as an expression (not recommended)

In native SQL, we can do it by following the following methods

select * from `orders` left join `users` on `orders`.`usename`=`users`.`usename` and `orders`.`platform`=`users`.`platform` where `orders`.`order_status` = 2

Then combined with laravel, we can

DB::select('select * from `orders` left join `users` on `orders`.`usename`=`users`.`usename` and `orders`.`platform`=`users`.`platform` where `orders`.`order_status` = :id', ['id' => 1]);

2. Use advanced Join syntax (recommended)

We only need the following code to complete our Join multiple conditions

DB::table('users')
  ->join('contacts', function ($join) {
    $join->on('', '=','contacts.user_id')->on('', '=','');
    })
  ->get();

If you want to know more, we can take a look at the description in the documentation:

Let's start by passing in a closure as the second parameter of the join method. This closure receives a JoinClause object, allowing you to specify constraints on the join clause:

DB::table('users')
  ->join('contacts', function ($join) {
    $join->on('', '=','contacts.user_id')->orOn(...);
    })
  ->get();

If you want to use "where" style clauses in a connection, you can use the where and orWhere methods in the connection. These methods compare fields with one value instead of comparisons between two fields:

DB::table('users')
    ->join('contacts', function ($join) {
      $join->on('', '=', 'contacts.user_id')
         ->where('contacts.user_id', '>', 5);
    })
    ->get();

The above detailed explanation of the advanced Join grammar of laravel and the multiple conditions for using Join are all the content I share with you. I hope you can give you a reference and I hope you can support me more.