doudao1950 2015-04-12 16:48
浏览 162
已采纳

在Laravel 5中合并'with'和'whereHas'

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

$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 with their filtered submissions, which has any of them. However, it seems wasting to run both whereHas and with methods with the same callback function. Is there a way to simplify it?

Thanks.

  • 写回答

3条回答 默认 最新

  • dongnai1876 2015-04-12 20:03
    关注

    In terms of performance you can't really optimize anything here (except if you were to move from eloquent relations to joins). With or without whereHas, two queries will be run. One to select all users another one to load the related models. When you add the whereHas condition a subquery is added, but it's still two queries.

    However, syntactically you could optimize this a bit by adding a query scope to your model (or even a base model if you want to use this more often):

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

    Usage:

    User::withAndWhereHas('submissions', function($query) use ($id){
        $query->where('taskid', $id);
    })->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?