![](/img/trans.png)
[英]How to show has many relation record in Yii2 GridView and DetailView?
[英]how to check yii2 relation is exist show controller
我有用户和代理商模型
用户具有代理商模型,可以访问$ user-> agency
现在我想在关系存在时检查accessRule显示我的控制器(如果该关系为null)显示警报'user-> agency is null pealse create agency',然后将用户传递给代理控制器
在用户模型中,我有这种关系:
public function getAgency(){
return $this->hasOne(Agency::className(),['id'=>'agency_id'])
->viaTable(self::MAP_TABLE,['user_id'=>'id']);
}
我有这个accessRule组件:
namespace common\components;
use common\models\User;
class AccessRule extends \yii\filters\AccessRule {
/**
* @inheritdoc
*/
protected function matchRole($user)
{
if (empty($this->roles)) {
return true;
}
foreach ($this->roles as $role) {
if ($role == '?') {
if ($user->getIsGuest()) {
return true;
}
}
elseif (!$user->getIsGuest()) {
$userObj = User::findOne(['id'=>$user->getId()]);
if ($role == User::AGENCY_USER) {
if ( $userObj->agency_perm >= User::AGENCY_USER) {
return true;
}
// Check if the user is logged in, and the roles match
} elseif ($role == User::AGENCY_MODERATOR) {
if ( $userObj->agency_perm >= User::AGENCY_MODERATOR) {
return true;
}
// Check if the user is logged in, and the roles match
} elseif ($role == User::AGENCY_ADMIN) {
if ($userObj->agency_perm >= User::AGENCY_ADMIN) {
return true;
}
// Check if the user is logged in, and the roles match
} elseif ($role == User::SUPER_USER) {
if ($userObj->super_user == User::SUPER_USER) {
return true;
}
// Check if the user is logged in, and the roles match
} elseif (!$user->getIsGuest() && $role == $user->identity->role) {
return true;
}
}
}
return false;
}
}
并在我的控制器中使用它:
'access' => [
'class' => AccessControl::className(),
// We will override the default rule config with the new AccessRule class
'ruleConfig' => [
'class' => AccessRule::className(),
],
'rules' => [
[
'allow' => true,
'roles' => [
User::SUPER_USER,
],
],
],
],
在Yii访问控制中,您可以通过以下方法检查用户访问权限:
construct()
方法 您可以在此级别检查您的自定义访问权限,然后选择授予访问权限或将他重定向到另一个页面。
第三种方式,您可以访问controller/action
名称,然后确定会发生什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.