Yii2排序对象defaultOrder

时间:2017-03-23 22:53:08

标签: yii2

我有一个属于章节的政策表。当我在网格视图中查看策略时,我希望默认顺序是章节标题中的策略标题。我看到如何设置排序属性来启用它,但我无法弄清楚如何将defaultOrder设置为基于章节标题,然后是策略标题。当我尝试将policy.title设置为defaultOrder设置中的属性时,我收到错误。

2 个答案:

答案 0 :(得分:1)

如果Policy是策略表的模型类,它与名为' chapter'的章节表有关系。并通过chapter_id字段链接,例如:

public function getChapter()
{
    return $this->hasOne(Chapter::className(), ['chapter_id' => 'chapter_id']);
}

现在构建查询对象,其策略与章节相结合:

$query = Policy::find()
->joinWith(['chapter']);

 $dataProvider = new ActiveDataProvider([
     'query' => $query,
     'sort'=> ['defaultOrder' => ['chapter.title'=>SORT_ASC, 'policy.title' => SORT_ASC]]
 ]);

答案 1 :(得分:0)

我无法得到Fabrizio的工作答案,因为我的章节表是policy_chapter,而不仅仅是章节,因此与关系名称不同。当我尝试使用关系名称时,我遇到了错误。我终于弄清楚了,你必须使用相关表的名称,而不是关系,并将它们作为属性添加。 e.g:

$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'pagination' => ['pageSize' => 50],
    'sort' => [
        'defaultOrder' => ['policy_chapter.sort' => SORT_ASC,'policy_chapter.title' => SORT_ASC],
        'enableMultiSort' => true,
        'attributes' => [
            'id' => [
                'asc' => ['policy.id' => SORT_ASC],
                'desc' => ['policy.id' => SORT_DESC],
                'default' => SORT_ASC
            ],
            'chapter_id' => [
                'asc' => ['policy_chapter.sort' => SORT_ASC,'policy_chapter.title' => SORT_ASC],
                'desc' => ['policy_chapter.sort' => SORT_DESC,'policy_chapter.title' => SORT_DESC],
                'default' => SORT_ASC,
            ],
            'reference' => [
                'asc' => ['reference' => SORT_ASC],
                'desc' => ['reference' => SORT_DESC],
                'default' => SORT_ASC
            ],
            'title' => [
                'asc' => ['policy.title' => SORT_ASC],
                'desc' => ['policy.title' => SORT_DESC],
                'default' => SORT_ASC
            ],
            'policy_chapter.sort',
            'policy_chapter.title',
        ],
    ],
]);

使用关系名称或省略属性,您会收到错误。在我写作之前

'defaultOrder' => ['policy_chapter.sort' => SORT_ASC,'policy_chapter.title' => SORT_ASC],

和Yii不高兴