【发布时间】:2016-04-25 16:55:36
【问题描述】:
经典表:用户、auth_item(用于角色/权限)、多对多用户的 auth_assignment 联结角色。
我关注(或试图关注)文档和其他人的问题。我想出了以下内容(我的 ActiveRecord 测试的类有一个“Ar”前缀):
在“用户”模型中(models/Aruser.php):
public function getRoles() {
return $this->hasMany(ArauthItem::className(), ['name' => 'item_name'])
->viaTable('auth_assignment', ['user_id' => 'id']);
}
在“角色”模型中,即 auth_item 表模型 (models/ArauthItem.php):
public function getUsers() {
return $this->hasMany(Aruser::className(), ['id' => 'user_id'])
->viaTable('auth_assignment', ['item_name' => 'name']);
}
在“用户搜索”模型中(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 在一列中显示多对多连接的方式是什么?我做错了什么?
非常感谢!
【问题讨论】: