Jinzhao Huo
Jinzhao Huo

Reputation: 857

Add case when statement in Yii SQL command object

In YII, I have a already working function:

$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');

Now I am trying to add a tiny logic to the product_name field, in MYSQL it would be

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

Is it possible to add this case when block in the select() function?

Upvotes: 6

Views: 4861

Answers (1)

Jinzhao Huo
Jinzhao Huo

Reputation: 857

I asked the question here after struggling for 2 hours by googled and searched a lot here. But 10 minutes later, I found I've got the answer...

After taking a look at the source code of select() method,

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;
}

Pay attention to the 1st if statement, when a string is passed and it contains "(", the $columns variable will be returned directly, that's really what I am looking for!

So the solution will be:

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

Take care that the alias part "as product_name" should be out of () section.

Upvotes: 10

Related Questions