如何根据yii2查询生成器中基于子查询的条件写入条件

时间:2018-03-28 07:17:55

标签: yii yii2 yii2-advanced-app yii2-basic-app yii2-model

我在主查询中有一个子查询,如下所示:

$subquery = (new Query())->select('COUNT(project_sup_id)')
    ->from('project_supervisors AS sup')
    ->where(['AND','sup.project_ref_id = p.project_id']);

$uQuery =(new Query())->select(['project_id','supcount' => $subquery])
    ->from('projects AS p')
    ->join('LEFT JOIN','project_supervisors AS sup','sup.project_ref_id = project_id')
    ->andWhere('IF(supcount>0, sup_project_status=1, project_status=1)');

我正在尝试根据逻辑写出条件,即,如果从子查询获得的计数大于零,那么条件必须是sup_project_status=1其他project_status=1。在普通的Mysql中,如果条件在哪里,很容易写,但是在yii2我不理解如何写。

1 个答案:

答案 0 :(得分:0)

尝试将yii \ db \ Expression用于RDBMS本机表达式:

->andWhere(new yii\db\Expression('IF(supcount>0, sup_project_status=1, project_status=1)'));

您可以使用以下方法检查SQL:

echo $uQuery->createCommand()->getRawSql();

它返回Query对象准备好的SQL命令。您也可以将整个SQL编写为yii \ db \ Command:

$count = Yii::$app->db->createCommand('SELECT count(...) FROM ... WHERE ...')->queryScalar();