laravel - 具有多个 where 条件的 Laravel 动态查询
问题描述
以下使用 Laravel 构建的查询不起作用(它不返回任何记录):
$this->projectstages = ProjectBuildStage::leftJoin('projects', 'projects.id', '=', 'project_build_stages.project_id')
->leftJoin('build_stages as bs', 'bs.id', '=', 'project_build_stages.build_stage_id')
->leftJoin('build_stage_types as bst', 'bst.build_stage_id', '=', 'bs.id')
->select('bs.build_stage', 'bst.build_stage_type', 'bst.id as build_stage_type_id', 'bs.id')
->where('projects.id', $ProjectId)
->where('bst.project_id',$ProjectId);
if ($buildstageId != 0 && $buildstageId != null && $buildstageId != 'all') {
$this->projectstages->where('bs.id', '=', $buildstageId);
}
$this->projectstages->orderBy('bs.sort_order', 'asc')->orderBy('bst.sort_order', 'asc');
$this->projectstages->get();
ToSQL 结果:
"select `bs`.`build_stage`, `bst`.`build_stage_type`, `bst`.`id` as `build_stage_type_id`, `bs`.`id` from `project_build_stages` left join `projects` on `projects`.`id` = `project_build_stages`.`project_id` left join `build_stages` as `bs` on `bs`.`id` = `project_build_stages`.`build_stage_id` left join `build_stage_types` as `bst` on `bst`.`build_stage_id` = `bs`.`id` where `projects`.`id` = ? and `bst`.`project_id` = ? and `bs`.`id` = ? and `project_build_stages`.`company_id` = ? order by `bs`.`sort_order` asc, `bst`.`sort_order` asc ◀"
但是,如果我删除if并将查询变成单个语句,它将起作用:
$this->projectstages = ProjectBuildStage::leftJoin('projects', 'projects.id', '=', 'project_build_stages.project_id')
->leftJoin('build_stages as bs', 'bs.id', '=', 'project_build_stages.build_stage_id')
->leftJoin('build_stage_types as bst', 'bst.build_stage_id', '=', 'bs.id')
->select('bs.build_stage', 'bst.build_stage_type', 'bst.id as build_stage_type_id', 'bs.id')
->where('projects.id', $ProjectId)
->where('bst.project_id',$ProjectId)
->orderBy('bs.sort_order', 'asc')
->orderBy('bst.sort_order', 'asc')
->get();
ToSQL 结果:
"select `bs`.`build_stage`, `bst`.`build_stage_type`, `bst`.`id` as `build_stage_type_id`, `bs`.`id` from `project_build_stages` left join `projects` on `projects`.`id` = `project_build_stages`.`project_id` left join `build_stages` as `bs` on `bs`.`id` = `project_build_stages`.`build_stage_id` left join `build_stage_types` as `bst` on `bst`.`build_stage_id` = `bs`.`id` where `projects`.`id` = ? and `bst`.`project_id` = ? and `bs`.`id` = ? and `project_build_stages`.`company_id` = ? order by `bs`.`sort_order` asc, `bst`.`sort_order` asc ◀"
谁能指出我在第一个例子中做错了什么?第二个工作得很好,但第一个不返回任何记录
谢谢!
解决方案
推荐阅读
- php - 如何使用php获取数组中文件的扩展名
- android - 在图标顶部显示工具提示箭头,该箭头是对齐 TextView 中文本的结尾
- ios - 是否可以通过 IPA 文件永久安装应用程序?
- python - 从包中多次导入的 PEP8 建议是什么?
- android - Flutter 如何抓取网站上的图片源元素
- jquery - 日期格式在jquery中获取系统时间格式
- python - VS Code (Mac) - 有/没有虚拟环境的一致 Python 解释器问题
- sql - 停止打印双精度值 SQL
- protractor - ReferenceError:驱动程序未在量角器中定义
- loops - 如何使用守夜人获取动态 Excel 的行数(不包括标题)