在 Laravel 5 中合并“with"和“whereHas"

Merge #39;with#39; and #39;whereHas#39; in Laravel 5(在 Laravel 5 中合并“with和“whereHas)
本文介绍了在 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();

基本上,我们的目标是只获取那些过滤提交的用户,其中包含其中任何一个.但是,使用相同的回调函数同时运行 whereHaswith 方法似乎是浪费.有什么办法可以简化吗?

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"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)