问题描述
我在 Laravel 5 中有这段代码,使用 Eloquent,效果很好:
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();
基本上,我们的目标是只获取那些过滤提交的用户,其中包含其中任何一个.但是,使用相同的回调函数同时运行 whereHas 和 with 方法似乎是浪费.有什么办法可以简化吗?
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?
谢谢.
推荐答案
就性能而言,您无法真正优化此处的任何内容(除非您要从 eloquent 关系转向连接).不管有没有 whereHas
,都会运行两个查询.一个选择所有用户,另一个加载相关模型.当您添加 whereHas
条件时,会添加一个子查询,但它仍然是两个查询.
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]);
}
用法:
User::withAndWhereHas('submissions', function($query) use ($id){
$query->where('taskid', $id);
})->get();
这篇关于在 Laravel 5 中合并“with"和“whereHas"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!