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.

3 Answers 3

33

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]);
}
1
  • 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(); Oct 5, 2021 at 5:26
4

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();
1
  • 1
    inside the with() are Bracktes missing []
    – kasoft
    Oct 11, 2018 at 11:58
1

Use like.......

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

Reference

5
  • check your id and then run?
    – vishuB
    Dec 30, 2015 at 12:12
  • check this compare id ['device_id' => 'id']
    – vishuB
    Dec 30, 2015 at 12:33
  • wich?, hasMany relation, viaTable? or I have to set it in andWhere clousure?
    – Sageth
    Dec 30, 2015 at 12:36
  • refer this link....stackoverflow.com/questions/27690401/…
    – vishuB
    Dec 30, 2015 at 12:52
  • But in this link, he had a N:M relation, and i have 1:N
    – Sageth
    Dec 30, 2015 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.