yii2 GridView多对多的联结表显示

时间:2016-04-25 16:55:37

标签: gridview yii2

经典表格:用户,auth_item(针对角色/权限),针对多对多用户的auth_assignment结点< - >角色。

我跟随(或试图跟随)文档和其他人'的问题。我提出了以下内容(我的ActiveRecord测试的类有一个" Ar"前缀):

用户"用户" model(models / Aruser.php):

public function getRoles() {
    return $this->hasMany(ArauthItem::className(), ['name' => 'item_name'])
      ->viaTable('auth_assignment', ['user_id' => 'id']);
}

In"角色" model,又名auth_item表模型(models / ArauthItem.php):

public function getUsers() {
    return $this->hasMany(Aruser::className(), ['id' => 'user_id'])
      ->viaTable('auth_assignment', ['item_name' => 'name']);
}

在"用户搜索" model(models / ArusersSearch.php):

class AruserSearch extends Aruser{  
public $roles;    

public function rules()
{
    return [
        [['id', 'status', 'created_at', 'updated_at'], 'integer'],
        [['username', 'auth_key', 'password_hash', 'password_reset_token', 'email','roles'], 'safe'],
    ];
}

public function search($params)
{
    $query = Aruser::find();
    $query->joinWith(['roles']);

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

   /* ... some skipped code, the usual ... */

    $query->andFilterWhere(['like', 'username', $this->username])
        ->andFilterWhere(['like', 'auth_key', $this->auth_key])
        ->andFilterWhere(['like', 'password_hash', $this->password_hash])
        ->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])
        ->andFilterWhere(['like', 'email', $this->email])
        ->andFilterWhere(['like', 'auth_item.name', $this->roles]);

    return $dataProvider;
}

}

最后,在视图文件中:

GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'username',
        'auth_key',
        'password_hash',
        'password_reset_token', 
        'roles.name',

        /*
        [
         'attribute' => 'roles',
         // this is an anonymous function built by me to retrieve correct concatanated related m to n values, but is it the proper and correct way?
         'value' => function ($model) {     
                    $multiple_res = '';
                    foreach($model->roles as $role){
                        $multiple_res .= ($multiple_res?',':'').$role->name;
                    }
                    return $multiple_res;
                },              
         ],
         */

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

除非我使用您可以看到上面评论的匿名函数,否则我无法让角色列显示除"(未设置)"之外的任何内容。什么是Yii2> GridView在一列中显示多对多连接的方式?我做错了什么?

非常感谢!

1 个答案:

答案 0 :(得分:1)

使用匿名函数是正确的方法。就我所知,Yii并不支持你所说的功能。

但我会简化你的功能:

'value' => function($model) {
    return implode(", ", array_map(function($ar){
            return $ar->name;
    }, $model->roles));
}