Yii2 RBAC权限自己的岗位


Yii2 RBAC Permission Own post

我想为创建帖子/类别的作者提供更新/删除帖子/类别的权限

我不知道,我必须在这里给出第二个参数。I tried:

$post=new Post();
       if (Yii::$app->user->can('updatePost',['Post'=>$post])) 

但是得到错误获取未知属性:common'models'Post::createdBy

My Class AuthorRule:

class AuthorRule extends Rule
{
public $name = 'isAuthor';
/**
 * @param string|integer $user the user ID.
 * @param Item $item the role or permission that this rule is associated with
 * @param array $params parameters passed to ManagerInterface::checkAccess().
 * @return boolean a value indicating whether the rule permits the role or permission it is associated with.
 */
public function execute($user, $item, $params)
{
    return isset($params['Post']) ? $params['Post']->CreatedBy->id == $user : false;
}
}
更新:

  • Post模型
  • <
  • RBAC控制器/gh>
  • AuthorRule
  • <
  • AuthItem表/gh><
  • AuthItemChild表/gh>
  • 身份验证任务

你在做正确的事情,将对象传递给规则。

您确定您的Post模型实际上具有createdBy属性吗?在你的另一段代码中,你有CreatedBy

很可能是拼写错误,或者您的Post模型没有该字段,或者它被称为不同的(created_by ?)

哦,还有一件事,如果CreatedBy是一个关系,并且对象不存在,尝试获取其属性(id)将产生错误。试试if (isset($params['Post']->CreatedBy) && $params['Post']->CreatedBy->id == $user) .