sqlyiiyii2query-builderyii2-active-records

Yii 2.0 query builder - Select text as column (without grave/back tick/back quote)


Asking a question that I've spent the last 2 hours trawling the internet to find and couldn't get a solution to, but finally figured out a solution so I'll post the answer here for future users.

If I'm using Yii's query builder but want to set a column to be a string of predefined text not a column itself. This happens when you use single quotes in the select statement, so it's both an issue for my date format as well as the 'All Sites' column.

$query = Department::find()
  ->alias('d')
  ->select("user_name, count(department) as departments, DATE_FORMAT(join_date, '%Y-%m') as join_date 'All Sites'")
  ->createCommand()
  ->getRawSql();

This returns:

Select user_name, count(department) as departments, DATE_FORMAT(join_date, `'%Y-%m')` AS `join_date` `'All Sites'` 
from `department_table` `d`

So how to I escape the 'All Sites' string and regex so that Yii doesn't inherently add back quotes


Solution

  • The solution to this is as follows. I found that to solution for my date_format doesn't work for the string of text, as such I've given both variations on escaping the back quote issue in case either will help you.

    Note that in order to use Expression you'll have to include:

    use yii\db\Expression;
    
    $query = Department::find()
                ->alias('d')
                ->select("user_name, count(department) as departments")
                ->addSelect(["DATE_FORMAT(join_date, '%Y-%m') as join_date"])
                ->addSelect(new Expression("'All sites'"))
                ->createCommand()
                ->getRawSql();
    

    This outputs the following query:

    Select  username, count(department) as department, DATE_FORMAT(join_date, '%Y-%m') as join_date, 'All Sites'
        FROM `department_table` `d`