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]);
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With