Answer the question
In order to leave comments, you need to log in
How to remove extra join in query builder?
There is a regular query to the database using query builder laravel
But also when getting a selection, a condition can be used
$user = USER::query
->where(active, '=', 1)
->join('roles', 'roles.user_id', '=', 'user_id')
->where(function ($query) {
if($roleId) {
$query->where('role', '=', $roleId)
}
})
->get()
$user = USER::query
->where(active, '=', 1)
->join('roles', function($join) {
if($roleId) {
$join->on('roles.user_id', '=', user.id)
}
})
->where(function ($query) {
if($roleId) {
$query->where('role', '=', $roleId)
}
})
->get()
Answer the question
In order to leave comments, you need to log in
$userQuery = USER::query()
->where(active, '=', 1);
if($roleId){
$userQuery->join('roles', 'roles.user_id', '=', 'user_id')
->where('role', '=', $roleId);
}
$user = $userQuery->get()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question