11

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.

Sageth
  • 1,102
  • 1
  • 15
  • 30

3 Answers3

32

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]);
}
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • Very useful to get another type of data since it returns an AR obj, such as user's last transaction : `orderBy('created_at DESC')->one();` – Prabowo Murti Oct 05 '21 at 05:26
3

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();
vkabachenko
  • 251
  • 3
  • 5
1

Use like.......

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

Reference

vishuB
  • 4,173
  • 5
  • 31
  • 49