Laravel-有没有一种方法可以将hasHas和 [英] Laravel - is there a way to combine whereHas and with
问题描述
我目前面临一个小问题.我只想在存在某些条件的关系时才返回模型.使用whereHas()方法很好用.
I'm currently facing a small problem. I want to return a model only if a relation with certain conditions exists. That's working fine with the whereHas()-method.
$m = Model
::whereHas(
'programs',
function($q) {
$q->active();
}
);
但是,将关系作为这样的属性进行调用会给我全部(未过滤的结果).
However, calling the relation as a property like this will give me all (not filtered results).
$m->programs;
所以基本上我现在正在做的是:
So basically what I'm doing now is this:
$m = Model
::whereHas(
'programs',
function($q) {
$q->active();
}
)
->with(array('programs' => function($q) {
$q->active();
}))
;
这很好,但是我对再次做同样的事情感到非常难过.那不是正确的方法.如何在不重复代码的情况下实现这一目标?
That's working fine but I feel very bad about doing the same thing again. That can't be the right way. How can I achieve this without kind of duplicating the code?
推荐答案
如果活动程序"的概念在您的应用程序中很重要,请考虑为活动程序创建一个单独的关系(在这种情况下,我想是有一个HasMany关系):
If a concept of an "active program" is important in your application, consider creating a separate relation just for active programs (in this case I'm presuming you have a HasMany relation):
class Model
{
public function activePrograms()
{
return $this->hasMany(Program::class)->active();
}
}
然后,您可以将查询简化为:
Then you can simplify your query to:
Model::with('activePrograms')->has('activePrograms')->get();
这篇关于Laravel-有没有一种方法可以将hasHas和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!