2016-04-25 71 views
1

经典表:用户,auth_item(用于角色/权限),auth_assignment结对多对多用户< - >角色。yii2 GridView多对多结点表显示

我遵循(或试图跟随)文档和其他人的问题。我想出了以下(我有我的课对我的ActiveRecord测试的“AR”前缀):

在“用户”模式(型号/ Aruser.php):

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

在“角色“模型,又名auth_item表型号(型号/ ArauthItem.php):

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

在 ”用户搜索“ 模型(模型/ 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

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

不过,我想简化你的功能,像这样:

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

谢谢ttdijkstra,只是一个小评:破灭在这里并不适用,$模型 - >角色是采取阵列 – dev299

+0

点的数组。我多么粗心。 – ttdijkstra

+0

谢谢ttdijkstra,这很有帮助。 – RezaGM