如何在 yii2 查询生成器中基于子查询在 where 条件中编写 if 条件
how to write if condition inside where condition based on subquery in yii2 query builder
我在主查询中有一个子查询,如下所示:
$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)');
我正在尝试根据逻辑编写 where 条件,即,如果从子查询获得的计数大于零,则 where 条件必须是 sup_project_status=1
else project_status=1
。普通的Mysql where里面的if条件写起来很容易,但是yii2里我不太明白怎么写。
尝试将 yii\db\Expression 用于 RDBMS-native 表达式:
->andWhere(new yii\db\Expression('IF(supcount>0, sup_project_status=1, project_status=1)'));
您可以使用以下方式检查您的 SQL:
echo $uQuery->createCommand()->getRawSql();
它returns 由 Query 对象准备了 SQL 命令。您也可以将整个 SQL 写为 yii\db\Command:
$count = Yii::$app->db->createCommand('SELECT count(...) FROM ... WHERE ...')->queryScalar();
我在主查询中有一个子查询,如下所示:
$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)');
我正在尝试根据逻辑编写 where 条件,即,如果从子查询获得的计数大于零,则 where 条件必须是 sup_project_status=1
else project_status=1
。普通的Mysql where里面的if条件写起来很容易,但是yii2里我不太明白怎么写。
尝试将 yii\db\Expression 用于 RDBMS-native 表达式:
->andWhere(new yii\db\Expression('IF(supcount>0, sup_project_status=1, project_status=1)'));
您可以使用以下方式检查您的 SQL:
echo $uQuery->createCommand()->getRawSql();
它returns 由 Query 对象准备了 SQL 命令。您也可以将整个 SQL 写为 yii\db\Command:
$count = Yii::$app->db->createCommand('SELECT count(...) FROM ... WHERE ...')->queryScalar();