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"
基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
