如何在Laravel控制器中实现这样的事情
function model_b(){
return $this->hasMany('App\ModelB');
}
假设我已经在模型A中完成了这样的关系
{{1}}
答案 0 :(得分:4)
如果要按whereHas()
中的字段过滤ModelA
,请使用ModelB
方法:
ModelA::with('model_b')
->whereHas('model_b', function($q) {
$q->where('field_from_model_b', true);
})
->get();
如果您只想过滤ModelB
数据:
ModelA::with(['model_b' => function($q) {
$q->where('field_from_model_b', true);
}])
->get();
答案 1 :(得分:2)
您可以通过这种方式访问关系查询。
$results = ModelA::with(['mobel_b' => function ($query) {
$query->where('field_from_model_b', true);
}])
->get()