Reputation: 459
I woud like get a column that doesn't exist but return error
Normal way is:
SELECT 1 AS flag....
in yii:
Model::find()->select("1 AS flag, ...)...
the problem is that the query return with apexes
SELECT `1` AS `flag`
I already tryed with array but is the same result.
how can I do?
Thanks, Gabriele.
Upvotes: 0
Views: 574
Reputation: 1697
I found a solution to this after spotting this nugget of detail in the Yii docs:
https://www.yiiframework.com/doc/api/2.0/yii-db-query#select()-detail
The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression)
So... if you're selecting a fixed string you could wrap the selected "column" in a string function such as LTRIM()
, which won't do anything except fool Yii into not quoting the string with backticks.
Model::find()->select("LTRIM(1) AS flag, ...)...
You also need to add flag
as a property of the model as previously suggested - then you can use the output of the query as $Model->flag
Upvotes: 1
Reputation: 5456
Apart from gmc answer, you can also declare the variable in your model class and then use it in query as alias.
class YourModelName extends ActiveRecord
{
public $flag;
}
Then your below query will work.
Model::find()->select("1 AS flag, ...)...
Hope it helped!
Upvotes: 1
Reputation: 3990
The function findBySql
might work for you:
$sql = 'SELECT 1 as flag ...';
$model = Model::findBySql($sql)->all();
Upvotes: 2