首页 > 解决方案 > 具有多个 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 ◀"

谁能指出我在第一个例子中做错了什么?第二个工作得很好,但第一个不返回任何记录

谢谢!

标签: laravel

解决方案


推荐阅读