Search code examples
phpmathyii2arithmetic-expressions

Yii2: How to do a math addition in a simple find() response?


I have an array (called products) created with the Yii2 find() function with two fields (called name and price) and I need to do a simple arithmetic addition: price + 5. But I don't know how to do it.

Using SQL is very easy but with Yii2 I don't know how to resolve it.

$products = Products::find()
    ->select([
        'name',
        'price',
        'price' + 5
    ])
    ->asArray()
    ->all();

Solution

  • The reason is because you need not to quote the expression , just use the \yii\db\Expression() inside your select() statement like below

    $products = Products::find()
        ->select(['name','price',new \yii\db\Expression('price+5')])
        ->asArray()
        ->all();
    

    You can even use it to exclude the discount on the price if price and discount are table fields, see below.

    $products = Products::find()
        ->select(['name', 'price', new \yii\db\Expression('price - discount')])
        ->asArray()
        ->all();
    

    apart from the syntax used above you can also wrap the whole selet statement inside the Expression like

    ->select([new \yii\db\Expression('name, price, price + 5')])