How to sort by related table field when sending Yii2 REST GET request

两盒软妹~` 提交于 2019-12-11 00:35:35

问题


I want to expand this question.

Basically I have users endpoint. But I am also returning data from the related profiles table. I am not expanding with profiles, I always want to return it. So I have fields method like this:

public function fields()
{
    $fields = parent::fields();
    $fields[] = 'profile';
    return $fields;
}

When I do GET request and demand sorting by profile.created_at field and user.status, it does not sort by profile.created_at.

GET v1/users?sort=-profile.created_at,status

Can this be achieved somehow ?

This is my current code:

/** @var $query ActiveQuery */
$query = User::find();

// get data from profile table
$query->innerJoinWith('profile');

// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'sort'  => ['defaultOrder' => ['id' => SORT_DESC]],
    'pagination' => [
        'pageSize' => 10,
    ],
]);

return $dataProvider;

回答1:


You have overridden 'sort' parameter of ActiveDataProvider. To keep default behaviour of Sort object and change defaultOrder property, create an instance, such as:

$sort = new \yii\data\Sort([
    'attributes' => [
        'profile.created_at',
    ],
    'defaultOrder' => ['id' => SORT_DESC],
]);

// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'sort'  => $sort,
    'pagination' => [
        'pageSize' => 10,
    ],
]);


来源:https://stackoverflow.com/questions/36474282/how-to-sort-by-related-table-field-when-sending-yii2-rest-get-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!