Model function order by related model

I have

public function getEmployeesRates(){
return $this->hasMany(EmployeesRates::className(), [‘EmpId’ => ‘EmpId’]);
}

but I need to return the values ordered based on 3 columns, 2 of which are from a related table.

EmployeesRates has a relationship with table Items where ItemId = ItemId

So I want return

return $this->hasMany(EmployeesRates::className(), [‘EmpId’ => ‘EmpId’])

with an Order By Items.Currency, Items.Desc, EmployeesRates.EffectiveAsOf DESC

How can I achieve this?

Clarify situation a bit. Do you have relations like this?
something->EmployeesRates->Items

If so, you can query the data similar to (didn’t test):

something::find()->with('employeesRates')->with('items')->orderBy([
'Items.Currency' => SORT_DESC,
'Items.Desc' => SORT_DESC,
'EmployeesRates.EffectiveAsOf' => SORT_DESC,
])->all();

Study:
https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#querying-data
https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#relational-data

1 Like

Understood, create a normal query and ditch the $this->hasMany() approach. Thanks.

Don’t has many return a query object where you can call orderBy(...)?