php - 在 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”?
解决方案
您可以实现两个表的 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.*');
推荐阅读
- android - 如何在文本视图中为字符串(突出显示、下划线)设置不同的字体大小
- django - 弹性 beantalk 中的 celery worker 出错(使用 django 和 SQS)[ImportError:curl 客户端需要 pycurl 库。]
- sql - 如何在 Visual Studio 查询生成器中修复“在查询表达式中无效使用 '.'、'!' 或 '()'”
- android - Android JSON parsing output issue
- vue.js - Vue Cli:npm install 后找不到模块“../package.json”错误
- php - Show the sum of product attributes JS wordpress
- node.js - 添加到 JSON 的新数据不断替换以前的数据
- android - I have KeySignature Error How To Solve This?
- css - flexbox容器内的图像(垂直对齐),如果父级改变大小(使用flexbox),则不会改变大小
- java - adding new property based on spring profile