Laravel获取关系有价值的模型集合 [英] Laravel get collection of models where relation has value

查看:41
本文介绍了Laravel获取关系有价值的模型集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的Laravel网络应用制作更详细的注册表格.
我有一个 Category Question Survey 模型.
类别 hasMany Question ,而 Question 属于 Survey .

类别:

 公共功能questions(){返回$ this-> hasMany('App \ Question');}公共函数getUsingAttribute(){返回$ this->问题->包含('survey_id',Survey :: current()-> id);} 

我目前在我的Category类中有一个 using 属性,但我想将此范围设为
.需要明确的是, Category :: using-> get()的预期返回将返回所有 Category ,其中至少一个问题具有 survey_id Survey :: current()

解决方案

我会使用 解决方案

I would do it with one of the the methods available to query a relationship existence, specifically the whereHas() method:

return $this->whereHas('questions', function ($query){
    $query->where('survey_id', Survey::current());
});

这篇关于Laravel获取关系有价值的模型集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆