Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add case when statement in Yii SQL command object

Tags:

php

yii

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?

like image 261
Jinzhao Huo Avatar asked Aug 30 '12 06:08

Jinzhao Huo


People also ask

How to write query in yii?

use createcommand() method: use yii\db\Query(); $connection = \Yii::$app->db; $query = new Query; $insql = $connection->createCommand("SELECT* FROM inventory ); $result=$insql->queryAll(); the above method list all data from the inventory table.

How to write SQL query in yii2?

Call yii\db\QueryBuilder to generate a SQL statement based on the current construct of yii\db\Query; Create a yii\db\Command object with the generated SQL statement; Call a query method (e.g. queryAll()) of yii\db\Command to execute the SQL statement and retrieve the data.

How to create command in yii2?

A command object is usually created by calling yii\db\Connection::createCommand(). The SQL statement it represents can be set via the $sql property. To execute a non-query SQL (such as INSERT, DELETE, UPDATE), call execute().

How to connect database in yii framework?

Creating a Database Connection Step 1 − To create a database connection, you need to create an instance of the yii\db\Connection class. $mydb = new yii\db\Connection([ 'dsn' => 'mysql:host=localhost;dbname=mydb', 'username' => 'username', 'password' => 'password', 'charset' => 'utf8', ]);


1 Answers

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.

like image 125
Jinzhao Huo Avatar answered Sep 20 '22 00:09

Jinzhao Huo