发送Yii2 REST GET请求时如何按相关表字段排序

时间:2016-04-07 11:03:48

标签: rest sorting activerecord yii2

我想展开this question

基本上我有users个端点。但我也从相关的profiles表中返回数据。我没有扩展配置文件,我总是希望返回它。所以我有这样的字段方法:

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

当我通过profile.created_at字段和user.status进行GET请求并要求排序时,它不会按profile.created_at排序。

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

这可以通过某种方式实现吗?

这是我目前的代码:

/** @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 个答案:

答案 0 :(得分:1)

你已经覆盖了' sort' ActiveDataProvider的参数。要保持Sort对象的默认行为并更改defaultOrder属性,请创建一个实例,例如:

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