2

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;
Community
  • 1
  • 1
black-room-boy
  • 659
  • 2
  • 11
  • 23

1 Answers1

3

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,
    ],
]);
Fabrizio Caldarelli
  • 2,982
  • 11
  • 14
  • This doesn't do anything different than my code posted above. I still can't sort by profile.created_at – black-room-boy Apr 07 '16 at 13:06
  • How do you disambiguate columns? I have created_at in users table, and created_at in profile table, and want to sort by profile.created_at. This does not work: `$sort = new \yii\data\Sort([ 'attributes' => [ 'profile.created_at', ], 'defaultOrder' => ['profile.created_at' => SORT_DESC], ]);` Its says undefined index – black-room-boy Apr 07 '16 at 13:59