Laravel查询关系where子句

时间:2017-07-26 03:17:25

标签: php laravel orm eloquent

我需要按照惯例过滤,例如where('departamento_id', '=', 1)

表:

membro_bancas
id
departamento_id
user_id


trabalhos
id
titulo
orientador_id (references id of membro_bancas)
coorientador_id (references id of membro_bancas)

我有这段代码:

$trabalho = Trabalho::with('membrobanca.departamento')
    ->with('coorientador')
    ->with('academico')
    ->get();

并返回:

enter image description here

2 个答案:

答案 0 :(得分:1)

使用而非

尝试这个雄辩的过滤器
$trabalho = Trabalho::whereHas('membrobanca',function($query) use ($id){
     $query->where('departamento_id', '=', $id)
})
->with('coorientador')
->with('academico')
->get();

使用

进行过滤的示例
$trabalho = Trabalho::with(['membrobanca',function($query) use ($id){
     $query->where('departamento_id', '=', $id)
}])
->with('coorientador')
->with('academico')
->get();

答案 1 :(得分:1)

我明白了!

我也需要为orWhereHas添加coorientador。结果如下:

Trabalho::whereHas('membrobanca', function($q) use ($departamento_id) {
    $q->where('departamento_id', '=', $departamento_id);
})
->orWhereHas('coorientador', function($q) use ($departamento_id) {
    $q->where('departamento_id', '=', $departamento_id);
})
->with('academico')
->get();
相关问题