我怎样才能在 Laravel Controller 中实现这样的事情
$results = ModelA::with('model_b')->where('model_b.field_from_model_b',true)->get()
假设我已经像这样在模型 A 中建立了关系
function model_b(){
return $this->hasMany('App\ModelB');
}
最佳答案
如果您想通过 ModelB
中的字段过滤 ModelA
,请使用 whereHas()
方法:
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();
关于mysql - 如何在 Laravel 中创建 where 语句以匹配来自另一个模型的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48962618/