Combine 'with' and 'whereHas' in Laravel 5

I have this code in Laravel 5 using Eloquent, which works fine:

$filterTask = function($query) use ($id) {
    $query->where('taskid', $id);
};

User::whereHas('submissions', $filterTask)->with(['submissions' => $filterTask])->get();

Basically, the goal is to get only those users who have their own filtered materials, in which there are any of them. However, it seems like wasting time running both whereHas and using the same callback function. Is there any way to simplify it?

Thank.

+14
source share
3 answers

( , ). whereHas . , , . whereHas, , .

, ( , ):

public function scopeWithAndWhereHas($query, $relation, $constraint){
    return $query->whereHas($relation, $constraint)
                 ->with([$relation => $constraint]);
}

:

User::withAndWhereHas('submissions', function($query) use ($id){
    $query->where('taskid', $id);
})->get();
+32

" " (Laravel 5. 4+)

boot() .

\Illuminate\Database\Eloquent\Builder\Eloquent::macro('withAndWhereHas', function($relation, $constraint){
    return $this->whereHas($relation, $constraint)->with([$relation => $constraint]);
});
+1

I want to extend the answer from @lukasgeiter using static functions.

public static function withAndWhereHas($relation, $constraint){
    return (new static)->whereHas($relation, $constraint)
        ->with([$relation => $constraint]);
}

Usage is the same

User::withAndWhereHas('submissions', function($query) use ($id){
    $query->where('taskid', $id);
})->get();
0
source

All Articles