Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort hasMany relation in Yii2

Tags:

php

yii2

I have a simple relation 1:N to get some prices from a single model.

public function getPrices()
    {
        return $this->hasMany(Prices::className(), ['device_id' => 'id']);
    }

But I need prices objects sorteds by a specific property in this case $value

I've seen multiple examples in Yii 1 but nothing in Yii 2

Thanks to @vishu i've tried this:

public function getPrices()
{
    return $this->hasMany(Prices::className(), ['device_id' => 'id'])
        ->viaTable(Prices::tableName(), ['device_id' => 'id'], function ($query) {

            $query->orderBy(['device_price' => SORT_DESC]);
        });

}

But now it returns a empty array.

like image 784
Sageth Avatar asked Dec 30 '15 11:12

Sageth


2 Answers

I think you can assign the order by directly in relation

public function getPrices()
{
    return $this->hasMany(Prices::className(), ['device_id' => 'id'])->
      orderBy(['device_price' => SORT_DESC]);
}
like image 86
ScaisEdge Avatar answered Oct 06 '22 20:10

ScaisEdge


Setting order directly in relation may not be reliable in particular cases. So you can set order in AR query

Device::find()
->where(['id' => $id])
->with('prices' => function(\yii\db\ActiveQuery $query) {
    $query->orderBy('device_price DESC');
})
->one();
like image 29
vkabachenko Avatar answered Oct 06 '22 18:10

vkabachenko