简体   繁体   中英

Sort hasMany relation in 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.

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]);
}

Use like.......

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

Reference

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM