Laravel - is there a way to combine whereHas and with

只愿长相守 提交于 2020-01-02 08:31:07

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/34711549/laravel-is-there-a-way-to-combine-wherehas-and-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!