What is recommended way to sort collection by related column?

I have simplest relation between 2 tables.
Item table has: id, identifier, type_id
Type table has id, name

I use expand=type to get type names. I want to sort items by type.name.
What is recommended way to do that?

[
    {
        "identifier": "item 1",
        "type": {
            "name": "type C"
        }
    },
    {
        "identifier": "item 2",
        "type": {
            "name": "type A"
        }
    },
    {
        "identifier": "item 3",
        "type": {
            "name": "type B"
        }
    }
]

Sort it at model level. If it is a relation call orderBy in relation method

public function getTypes()
{
    return $this->hasMany(Type::className(), ['id' => 'identifier'])
                ->orderBy('name DESC');
}

I need to do that dynamically: ?expand=type&sort=type.name or &sort=-type.name
What is easiest way to do that?

Never done that before and not sure if it works or not.
I’ll leave that to whoever is more competent.
I will however suggest creating new action with sort as query string and do it manually!

In your data provider you can prepare custom attribute and add it as a sort option like

new ActiveDataProvider(
[
    // ...
    'sort' => [
        // ...
        'attributes' => [
            // ...
            'type.name' => [
                'asc' => ['xxx' => SORT_ASC],
                'desc' => ['xxx' => SORT_DESC],
                'default' => SORT_ASC,
            ],
    ],
]);

where xxx is the definition of the columns in relation (might be just type.name but I’m not sure how your db is configured).

2 Likes