4
$dataProvider = new ActiveDataProvider([
                'query' => UserProfile::find()->joinWith(['user'])->where(['<>', 'user.status', 0]),
                'sort' => ['attributes' => ['fullname',
                        'phone',
                        'user.username' => [
                            'asc' => ['user.username' => SORT_ASC],
                            'desc' => ['user.username' => SORT_DESC],
                            'default' => SORT_DESC
                        ],
                        'user.email' => [
                            'asc' => ['user.email' => SORT_ASC],
                            'desc' => ['user.email' => SORT_DESC],
                            'default' => SORT_DESC
                        ],
                    ]]
            ]);

排序fullnamephone工作良好。但我想在usernameemail列上添加排序。

请纠正我。

User 和 UserProfile 表有关系。(user_profile.user_id = user.id)

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            [
                'label' => 'Username',
                'value' => 'user.username',
            ],
            [
                'label' => 'Email',
                'value' => 'user.email',
            ],
            'fullname',
            'address',
            'phone',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
4

1 回答 1

3

您需要添加以下代码。还在搜索模型中添加公共变量。并将这些变量gridview用作属性名称。

public $username, $email;

public function rules()
{
    return [
        [['username', 'email'], 'safe'],
    ];
}

 $dataProvider = new ActiveDataProvider([
        'query' => UserProfile::find()->joinWith(['user'])->where(['<>', 'user.status', 0]), 
        'sort' => [ 
            'defaultOrder' => ['user.id' => SORT_DESC] 
        ],
    ]);

$dataProvider->sort->attributes['username'] = [
        'asc' => ['user.username' => SORT_ASC],
        'desc' => ['user.username' => SORT_DESC],
        ];
$dataProvider->sort->attributes['email'] = [
        'asc' => ['user.email' => SORT_ASC],
        'desc' => ['user.email' => SORT_DESC],
        ];

gridview代码。

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        [
            'label' => 'Username', (if sort link not appear so, add comment label line)
            'attribute' => 'username',
            'value' => 'user.username',
        ],
        [
            'label' => 'Email', (if sort link not appear so, add comment label line)
            'attribute' => 'email',
            'value' => 'user.email',
        ],
        'fullname',
        'address',
        'phone',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
于 2015-09-14T11:44:56.827 回答