How to sort by related table field when sending Yi

2019-07-18 20:16发布

问题:

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,
    ],
]);