Laravel Eloquent inner join with multiple conditions
To perform an inner join with multiple conditions using Laravel's Eloquent ORM, you can use the join
method on a query builder instance. Here's an example:
<?php
$users = DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')->orOn('users.id', '=', 'contacts.manager_id');
})
->get();
This will perform an inner join between the users
and contacts
tables, using the $join
closure to specify the join conditions. The orOn
method allows you to specify additional conditions for the join using an OR statement.
You can also use the where
method in the closure to specify additional conditions for the join, like this:
<?php
$users = DB::table('users')
->join('contacts', function ($join) {
$join
->on('users.id', '=', 'contacts.user_id')
->orOn('users.id', '=', 'contacts.manager_id')
->where('contacts.user_id', '>', 5);
})
->get();
This will perform the inner join with the additional condition contacts.user_id > 5
.
I hope this helps! Let me know if you have any questions.