【问题标题】:Laravel query relationship where clauseLaravel 查询关系 where 子句
【发布时间】:2017-07-26 03:17:24
【问题描述】:

我需要按部门过滤,例如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();

然后返回:

【问题讨论】:

  • 尝试做 $trabalho = Trabalho::with('membrobanca.departamento') ->with('coorientador') ->with('academico') ->where('membrobanca.departamento.departamento_id ', '=' , 1) ->get();
  • 顺便说一句,您要过滤哪个 ID?是在“membrobanca”还是在“departamento”?
  • 有什么区别?因为我需要用你的 Academicos、membrobancas 和 coorientador 检索所有 Trabalhos,并按 departamento of membrobanca 过滤
  • 如果是这种情况,那么您可以编写所有过滤器。所以,例子。 ->where('coorientador.departamento_id', '=', 1) ->where('membrobancas.departamento_id', '=', 1)
  • 不,很遗憾。

标签: php laravel orm eloquent


【解决方案1】:

我明白了!

我也需要为coorientador 添加orWhereHas。结果是这样的:

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();

【讨论】:

    【解决方案2】:

    使用 whereas

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

    使用 with

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

    【讨论】:

    • 谢谢!!!适用于 membrobanca 以及如何适用于 coorientador?我尝试为 coorientador 添加whereHas,但没有成功...
    • 你需要为 coorientador 过滤什么?
    猜你喜欢
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多