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在一列中顯示多對多連接的方式?我究竟做錯了什麼?
非常感謝!
謝謝ttdijkstra,只是一個小評:破滅在這裏並不適用,$模型 - >角色是採取陣列 – dev299
點的數組。我多麼粗心。 – ttdijkstra
謝謝ttdijkstra,這很有幫助。 – RezaGM