gpt4 book ai didi

yii - 如何在yii2查询构建器中基于子查询在where条件中编写if条件

转载 作者:行者123 更新时间:2023-12-04 03:20:30 27 4
gpt4 key购买 nike

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

$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否则 project_status=1 .在普通的Mysql中,很容易在where里面写if条件,但在yii2中我不明白如何写。

最佳答案

尝试将 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();

关于yii - 如何在yii2查询构建器中基于子查询在where条件中编写if条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49528333/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com