首页 > 解决方案 > 在 Laravel 的 Eloquent 查询中使用“with”时如何添加 where 子句

问题描述

我在使用“with”来包含相关模型的地方构建了一个查询。但是,我不确定如何在 where 子句中过滤这些相关模型。

return \App\Project::with("projectLeaders")->join('companies', 'company_id', '=', 'companies.id')
                        ->join('project_status', 'project_status.id', '=', 'projects.status_id')
                        ->select('companies.*', 'project_status.name AS statusName', 'projects.*');

请注意查询中的 with("projectLeaders")。因此,ProjectLeaders 是一个带来 Employee 类对象的关系,我如何在该查询中过滤那些属性“Lastname”类似于“Smith”的“Employees”?

标签: phplaravel

解决方案


您可以实现两个表的 where 类。请检查以下代码和注释。

return \App\Proyecto::with(["projectLeaders" => function($query){
  $query->where() //if condition with inner table.
}])->join('empresas', 'id_empresa', '=', 'empresas.id')
                        ->join('tipo_estado_proyecto', 'tipo_estado_proyecto.id', '=', 'proyectos.id_tipo_estado_proyecto')
  ->where() //if condition with main table column.
                        ->select('empresas.*', 'tipo_estado_proyecto.nombre AS nombreEstadoProyecto', 'proyectos.*');

推荐阅读