php - 在 Yii SQL 命令对象中添加 case when 语句

标签 php yii

在 YII 中,我有一个已经可以工作的函数:

$sql = Yii::app()->db->createCommand();
$sql->select('A.name as client_name, B.name as product_name');
$sql->join('tableb B', 'A.id=B.product_id');
$sql->from('tablea A');
$sql->where('1 = 1');

现在我想在 product_name 字段中添加一个小逻辑,在 MYSQL 中会是

CASE WHEN B.name = "sth"
THEN B.name 
ELSE B.another_name
END AS product_name

是否可以在 select() 函数中添加这个 case when block ?

最佳答案

我在谷歌上搜索了 2 小时后在这里问了这个问题,并在这里搜索了很多。但是 10 分钟后,我发现我找到了答案......

看了select()方法的源码后,

public function select($columns='*', $option='')
{
    if(is_string($columns) && strpos($columns,'(')!==false)
        $this->_query['select']=$columns;
    else
    {
        if(!is_array($columns))
            $columns=preg_split('/\s*,\s*/',trim($columns),-1,PREG_SPLIT_NO_EMPTY);

        foreach($columns as $i=>$column)
        {
            if(is_object($column))
                $columns[$i]=(string)$column;
            else if(strpos($column,'(')===false)
            {
                if(preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/',$column,$matches))
                    $columns[$i]=$this->_connection->quoteColumnName($matches[1]).' AS '.$this->_connection->quoteColumnName($matches[2]);
                else
                    $columns[$i]=$this->_connection->quoteColumnName($column);
            }
        }
        $this->_query['select']=implode(', ',$columns);
    }
    if($option!='')
        $this->_query['select']=$option.' '.$this->_query['select'];
    return $this;
}

注意第一个if语句,当传入一个字符串,其中包含“(”时,会直接返回$columns变量,这才是我要找的!

所以解决方案是:

$sql->select('A.name as client_name, (CASE WHEN B.name = "sth" THEN B.name ELSE B.product_name END ) as product_name');

注意别名部分“as product_name”应该在 () 部分之外。

关于php - 在 Yii SQL 命令对象中添加 case when 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12191043/

相关文章:

java - 如何将 Android 应用程序中的图像存储到 MySQL

php - 相关模型的 STAT 关系上的 STAT 关系,Yii

yii - 选择高性能PHP5框架

自动完成文本字段 CJuiAutoComplete 小部件 yii 存储隐藏字段 id 和显示名称

php - Yii NestedSetBehavior 内存使用情况

php - 使用 Doctrine 2.1 在数据库中保存 Zend 日期

php - 在 wordpress 中手动激活主题,网站无法访问

php - 相似词如何匹配?

php - Bash 补全 symfony

Yii2-具有ActiveRecord的表别名