I am working on the yii2 framework and I have an API from which I get "groups" from the table and it has a relationship with another table called "permissions" and this "permission" table has a foreign key for the "group" table "group_id" so for this the API is: http://localhost/yii2/backend/web/index.php?r=configuration/permissiongroup&expand=permissions&sort=name response: [
{
"id": 8,
"name": "group_a",
"permissions": [
{
"id": "34",
"name": "z",
"group_id": 8
},
{
"id": "35",
"name": "x",
"group_id": 8
},
{
"id": "36",
"name": "y",
"group_id": 8
}
]
},
{
"id": 3,
"name": "group_b",
"permissions": [
{
"id": "22",
"name": "b",
"group_id": 3
},
{
"id": "23",
"name": "d",
"group_id": 3
},
{
"id": "24",
"name": "a",
"group_id": 3
}
]
},
In this API I have managed to sort the "groups" object in ascending order by adding the "sort" parameter in the URL but I need to sort the "permissions" object in ascending order so how can I achieve that in the yii2 framework?
CodePudding user response:
I have managed to achieve this by the help of active query in the model of "permissionGroup" where I already had a function called "getPermissions" so I have just placed an orderBy and it worked.
public function getPermissions()
{
return $this->hasMany(Permission::className(), ['group_id' => 'id'])->orderBy('name ASC');
}
public function extraFields() {
return ['permissions'];
}
CodePudding user response:
You could use a pseudo attribute for sorting and set the appropriate sorting parameters for that.
The URL could be: http://localhost/yii2/backend/web/index.php?r=configuration/permissiongroup&expand=permissions&sort=name2
Configure the sorting like that:
$dataProvider->sort->attributes['name2'] = [
'asc' => [
'groups.name' => SORT_ASC,
'permissions.name' => SORT_ASC,
],
'desc' => [
'groups.name' => SORT_DESC,
'permissions.name' => SORT_DESC,
],
];