Merge 'with' and 'whereHas' in Laravel 5

前端 未结 3 1915
清歌不尽
清歌不尽 2020-11-29 05:37

I have this code in Laravel 5, using Eloquent, which is working perfectly:

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


        
3条回答
  •  粉色の甜心
    2020-11-29 05:55

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

提交回复
热议问题