1

I am working in YII2 Framework on the following query

SELECT T.id, T.name, T.status, IFNULL(T.image,'no-image.png') as DP
FROM TABLE_NAME T;

here is my code

$modelTeam = Teams::find()
    ->select(
        ['T.id', 'T.name', 'T.status', 'IFNULL(T.image,"no-image.png") as DP']
    )
    ->from('{{%teams}} T')
    ->all();

Edit:

The result set does not include DP column at all why is that so, and how can I do that.


Edit 2:

While telling that the results do not include the DP column I missed a piece of important information that I was using the ArrayHelper::toArray() to convert the model object to an array and then iterate over it

$results=ArrayHelper::toArray($modelTeam);
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68

3 Answers3

3

The actual problem is not where I was thinking it is, the query is alright, I used ArrayHelper::toArray($modelTeam) method to convert the model object to an array to further iterate over the array and display all the records, and that is where the problem lies.

I needed to use the second parameter $properties for the ArrayHelper::toArray(). The second argument converts properties mapping per class, as it has problems displaying the custom declared public properties of a model and the DP is declared public inside the Teams model as it is an alias in the ActiveRecrod query.

$modelTeam = Teams::find()->
    select(['TM.id', 'TM.name', 'TM.status'])
    ->addSelect([new \yii\db\Expression('IFNULL(TM.image,\'no-image.png\') AS DP')])
    ->from('{{%teams}} TM')->all();

$results = ArrayHelper::toArray($modelTeam, [
    'common\models\Teams' => [
        'id',
        'name',
        'status',
        'DP',
    ],
]);
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
1
$modelTeam = Teams::find()
    ->select(['T.id', 'T.name', 'T.status'])
    ->addSelect([new Expression('IFNULL(T.image,"no-image.png") as DP')])
    ->from('{{%teams}} T')
    ->all();
$arrTeam = $modelTeam->asArray()->all();
oaizumi
  • 11
  • 2
0

To use IFNULL in a select with Yii2 you must create a new expression.

$modelTeam = Teams::find()
    ->select(['T.id', 'T.name', 'T.status'])
    ->addSelect([new Expression('IFNULL(T.image,"no-image.png") as DP')])
    ->from('{{%teams}} T')
    ->all()
Miguel G. Flores
  • 802
  • 7
  • 21
  • With addSelect and having the new Expression into an array? What's the output? – Miguel G. Flores Oct 31 '16 at 23:04
  • here is complete code ` $modelTeam = Teams::find()-> select( ['T.id','T.name','T.status'] ) ->addSelect([new \yii\db\Expression('IFNULL(T.image,\'no-image.png\') AS DP')])-> from('{{%teams}} T')->all(); print_r(ArrayHelper::toArray($modelTeam));` outputs `Array ( [0] => Array ( [id] => 1 [name] => Pirates [status] => active ) ) ` – Muhammad Omer Aslam Oct 31 '16 at 23:06