如何在YII2中显示每个用户在我的索引和视图中的角色?
我的数据库中有所有RBAC表和一个用户表。 我在创建和更新用户时会分配一个角色,它会使用如何在YII2中显示每个用户在我的索引和视图中的角色?,yii2,Yii2,我的数据库中有所有RBAC表和一个用户表。 我在创建和更新用户时会分配一个角色,它会使用用户id为每个项目名称(角色)更新身份分配表 我的问题是-我想在我的用户/索引屏幕中有另一列,它将显示每个用户的角色,以及用户/视图 到目前为止,我尝试的一切都不起作用,我尝试加入用户和auth_分配表,但没有帮助-它说与auth_分配没有关系 守则: models/User.php <?php namespace app\models; use Yii; use \yii\web\IdentityI
用户id
为每个项目名称
(角色)更新身份分配表
我的问题是-我想在我的用户/索引
屏幕中有另一列,它将显示每个用户的角色,以及用户/视图
到目前为止,我尝试的一切都不起作用,我尝试加入用户和auth_分配
表,但没有帮助-它说与auth_分配
没有关系
守则:
models/User.php
<?php
namespace app\models;
use Yii;
use \yii\web\IdentityInterface;
use yii\helpers\ArrayHelper;
use app\models\Project;
/**
* This is the model class for table "user".
*
* @property integer $id
* @property string $username
* @property string $password
* @property string $auth_key
*/
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
/**
* @inheritdoc
*/
public $role;
public static function getRoles()
{
return ['admin'=>'admin','releaseManager'=>'releaseManager','pm'=>'pm','psw'=>'psw','qa'=>'qa'];
}
public function afterSave($insert,$changedAttributes)
{
$return = parent::afterSave($insert,$changedAttributes);
$auth = Yii::$app->authManager;
$roleName = $this->role;
$role = $auth->getRole($roleName);
if (\Yii::$app->authManager->getRolesByUser($this->id) == null)
{
$auth->assign($role, $this->id);
}
else
{
$db = \Yii::$app->db;
$db->createCommand()->delete('auth_assignment',['user_id' => $this->id])->execute();
$auth->assign($role, $this->id);
}
return $return;
}
public static function tableName()
{
return 'user';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username', 'password', 'auth_key'], 'string', 'max' => 255],
[['username', 'password','projectId','role'], 'required'],
[['username'], 'unique']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
'password' => 'Password',
'projectId' => 'Project Id',
'auth_key' => 'Auth Key',
/* 'role' => 'Role',*/
];
}
public static function findIdentity($id)
{
return static::findOne($id);
}
public static function findByUsername($username)
{
return static::findOne(['username' => $username]);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('You can only login
by username/password pair for now.');
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
public function validatePassword($password)
{
return $this->isCorrectHash($password, $this->password);
}
private function isCorrectHash($plaintext, $hash)
{
return Yii::$app->security->validatePassword($plaintext, $hash);
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
public function beforeSave($insert)
{
$return = parent::beforeSave($insert);
if ($this->isAttributeChanged('password'))
$this->password = Yii::$app->security->
generatePasswordHash($this->password);
if ($this->isNewRecord)
$this->auth_key = Yii::$app->security->generateRandomString(32);
return $return;
}
public function getProject()
{
return $this->hasOne(Project::className(), ['id' => 'projectId']);
}
/*public function getRole()
{
return $this->hasOne(User::findByUsername($username)->getId() );
}*/
public static function getUsers()
{
if (\Yii::$app->user->can('assignUsersToPost'))
{
$users = ArrayHelper::
map(self::find()->all(), 'id', 'username');
//$users[null] = "All Users";
} else {
$users = ArrayHelper::
map(self::find()->where(['id'=>Yii::$app->user->id])->all(), 'id', 'username');
}
return $users;
}
public static function getCurrentUser()
{
$user = ArrayHelper::
map(self::find()->where(['id'=>Yii::$app->user->id])->all(), 'id', 'username');
return $user;
}
/* public static function isSenderOrRciever($message)
{
$return = false;
if (
$message->fromUserId == Yii::$app->user->id
|| $message->toUserId == Yii::$app->user->id
)
$return = true;
return $return;
} */
}
“视图”
文件除了\u表单
外没有任何更改,因为我尝试的每件事都会给我一个错误。
据我所知,我只需要在index.php
和view.php
文件中添加一个代码,就可以让它正常工作,但已经一周了,我仍然没有找到解决方案
提前感谢,,
Jenny在GridView中,您始终可以使用返回所需数据的函数创建列。因此,在列定义的索引视图中添加以下内容:
[
'标题'=>'角色',
'value'=>函数($data){
$roles=\Yii::$app->authManager->getRolesByUser($data->id);
如果($角色){
返回内爆(“,”,数组_键($roles));
}否则{
返回“无角色”;
}
}
],
正如您在文档中所看到的,getRolesByUser
返回一个按角色名称索引的角色数组。这就是为什么我们使用键来显示角色
如果计划对该列进行筛选或排序,则必须实现适当的关系(getRole()
)。否则,您可以使用authManager
获取角色
但是,这不适用于DetailView,因为您无法向其传递函数。在这种情况下,您可以在模型中实现此功能:
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
//...
getRoleAsText()
{
$roles = \Yii::$app->authManager->getRolesByUser($this->id);
if ($roles) {
return implode(', ', array_keys($roles));
} else {
return 'no roles';
}
}
//...
}
之后,您可以在GridView和DetailsView中引用它:
['label'=>'Role','value'=>'roleAsText']
在GridView中,您始终可以使用返回所需数据的函数创建列。因此,在列定义的索引视图中添加以下内容:
[
'标题'=>'角色',
'value'=>函数($data){
$roles=\Yii::$app->authManager->getRolesByUser($data->id);
如果($角色){
返回内爆(“,”,数组_键($roles));
}否则{
返回“无角色”;
}
}
],
正如您在文档中所看到的,getRolesByUser
返回一个按角色名称索引的角色数组。这就是为什么我们使用键来显示角色
如果计划对该列进行筛选或排序,则必须实现适当的关系(getRole()
)。否则,您可以使用authManager
获取角色
但是,这不适用于DetailView,因为您无法向其传递函数。在这种情况下,您可以在模型中实现此功能:
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
//...
getRoleAsText()
{
$roles = \Yii::$app->authManager->getRolesByUser($this->id);
if ($roles) {
return implode(', ', array_keys($roles));
} else {
return 'no roles';
}
}
//...
}
之后,您可以在GridView和DetailsView中引用它:
['label'=>'Role','value'=>'roleAsText']
您可以使用以下函数返回带有索引roleName的用户角色数组
$roleArr = Yii::$app->authManager->getRolesByUser($data->userid);
您可以使用以下函数返回带有索引roleName的用户角色数组
$roleArr = Yii::$app->authManager->getRolesByUser($data->userid);
顺便说一句,使用返回实际模型或数据的方法(如
getUsers()
)通常是不方便的。更好的做法是使用返回查询的方法,然后在运行->all()
之前对这些查询进行修改。假设您的用户
模型返回一个所有帖子的列表作为一个模型数组。如果您希望只获取与特定条件匹配的模型,那么您应该首先获取所有模型,然后在PHP中丢弃其中一些模型。方法返回查询要好得多,这样您就可以使用->andWhere()
进一步修改它,只获取您需要的数据。顺便说一句,使用像您的getUsers()
这样返回实际模型或数据的方法通常是不方便的。更好的做法是使用返回查询的方法,然后在运行->all()
之前对这些查询进行修改。假设您的用户
模型返回一个所有帖子的列表作为一个模型数组。如果您希望只获取与特定条件匹配的模型,那么您应该首先获取所有模型,然后在PHP中丢弃其中一些模型。方法返回查询要好得多,这样您就可以使用->andWhere()
进一步修改它,并仅获取所需的数据。我现在尝试在视图中显示角色,但我得到了“htmlspecialchars()期望参数1为字符串,数组给定”错误。我将此代码添加到DetailView:['label'=>'Role','value'=>\Yii::$app->authManager->getRolesByUser($data->id),],我正在更新我的答案。我现在尝试在视图中显示角色,但我得到了“htmlspecialchars()期望参数1为字符串,数组给定”错误。我将此代码添加到DetailView:['label'=>'Role','value'=>\Yii::$app->authManager->getRolesByUser($data->id),],我正在更新我的答案。