本文介绍了在Laravel中合并'和'whereHas'5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ filterTask = function($ query )use($ id){
$ query-> where('taskid',$ id);
};

User :: whereHas('submissions',$ filterTask) - > with(['submissions'=> $ filterTask]) - > get();

基本上,目标是只让那些使用过滤提交的用户,其中有任何一个。
但是,使用具有相同回调函数的方法运行 whereHas 似乎很浪费。有没有办法简化?



谢谢。

解决方案

在性能方面,您无法真正优化任何内容(除非您从雄辩的关系转移到联接)。有或没有 whereHas ,将运行两个查询。一个选择所有用户另一个加载相关模型。当您添加 whereHas 条件时,添加一个子查询,但仍然是两个查询。



然而,在语法上你可以通过向您的模型添加(甚至如果您想要使用这个更频繁):

  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();


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.

解决方案

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();

这篇关于在Laravel中合并'和'whereHas'5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 04:41