如何在 Laravel 中使用 where 语句来匹配另一个模型中的字段

Aba*_*aan 1 mysql laravel eloquent

我怎样才能在 Laravel 控制器中实现这样的事情

$results = ModelA::with('model_b')->where('model_b.field_from_model_b',true)->get()
Run Code Online (Sandbox Code Playgroud)

假设我在模型 A 中做了这样的关系

function model_b(){
   return $this->hasMany('App\ModelB');
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*nin 5

whereHas()如果您想ModelA按 中的字段进行过滤,请使用该方法ModelB

ModelA::with('model_b')
    ->whereHas('model_b', function($q) {
        $q->where('field_from_model_b', true);
    })
    ->get();
Run Code Online (Sandbox Code Playgroud)

如果您只想过滤ModelB数据:

ModelA::with(['model_b' => function($q) {
        $q->where('field_from_model_b', true);
    }])
    ->get();
Run Code Online (Sandbox Code Playgroud)