Merge #39;with#39; and #39;whereHas#39; in Laravel 5(在 Laravel 5 中合并“with和“whereHas)
问题描述
我在 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"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Laravel 5 中合并“with"和“whereHas"
基础教程推荐
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01