Mysql 如何使where语句与Laravel中另一个模型的字段相匹配

Mysql 如何使where语句与Laravel中另一个模型的字段相匹配,mysql,laravel,eloquent,Mysql,Laravel,Eloquent,如何在Laravel控制器中实现这样的功能 $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('

如何在Laravel控制器中实现这样的功能

$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();
如果要按
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();

您可以通过这种方式访问关系查询

$results = ModelA::with(['mobel_b' => function ($query) {
    $query->where('field_from_model_b', true);
}])
->get()

您可以通过这种方式访问关系查询

$results = ModelA::with(['mobel_b' => function ($query) {
    $query->where('field_from_model_b', true);
}])
->get()