REST Attribute Mapping for Sort


(pupog30) #1

Hi,

I have 'number' => 'center_number' mapping in my fields() function. How can I sort using the ‘number’ attribute not the ‘center_number’.

https://172.16.1.21:7562/v1/centers?sort=-number
NOT
https://172.16.1.21:7562/v1/centers?sort=-center_number

ActiveDataFilter has attributeMap how about for sorting?

Thanks!


(demonking) #2

Can you provide some Code?


(pupog30) #3

Hello,

Here you go…

DB table:

+----------------------+-----------------------+------+-----+---------+----------------+
| Field                | Type                  | Null | Key | Default | Extra          |
+----------------------+-----------------------+------+-----+---------+----------------+
| center_id            | mediumint(8) unsigned | NO   | PRI | NULL    | auto_increment |
| location_description | varchar(200)          | NO   |     | NULL    |                |
| center_number        | mediumint(8) unsigned | NO   | UNI | NULL    |                |
| brand                | tinyint(3) unsigned   | NO   |     | NULL    |                |
+----------------------+-----------------------+------+-----+---------+----------------+

In Center model I have below fields:

public function fields()
{
    return [
        'id' => 'center_id',
        'name' => 'location_description',
        'number' => 'center_number',
        'brand',
    ];
}

Basically I just want to sort using the new fields like number not center_number.

I managed to do a similar stuff on filtering using ActiveDataFilter because it has ‘attributeMap’ property.

public function indexDataProvider(): ActiveDataProvider
    {
        $filter = new ActiveDataFilter([
            'searchModel' => CenterSearch::class,
            'attributeMap' => [
                'number' => 'center_number',
                'name' => 'location_description'
            ]
        ]);

… other codes ommitted …

So I can use https://172.16.1.21:7562/v1/centers?filter[number]=128 instead of https://172.16.1.21:7562/v1/centers?filter[center_number]=128

Can’t find anything similar with sorting.

Thanks!