S
S
snake22022-03-30 11:47:29
Laravel
snake2, 2022-03-30 11:47:29

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

Is it possible to somehow beautifully get rid of join if $roleId = null
So far, only such a solution comes to mind

$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

2 answer(s)
V
vism, 2022-03-30
@snake2

$userQuery = USER::query()
    ->where(active, '=', 1);
if($roleId){
    $userQuery->join('roles', 'roles.user_id', '=', 'user_id')
    ->where('role', '=', $roleId);
}
$user = $userQuery->get()

J
jazzus, 2022-03-30
@jazzus

Through relationships

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question