Yii 中的 rbac 授权检查不起作用(变得未知 属性:app\models\Post::createdBy)

rbac authorization check in Yii doesn't work (Getting unknown property: app\models\Post::createdBy)

我查看了 Yii 中 rbac 的文档,并认为在我实际尝试之前我了解它是如何工作的。

这是检查 post 的作者是否正在尝试获取操作授权的规则:

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['model']) ? $params['model']->createdBy == $user : false;
    }
}

这就是我尝试使用规则和 Yii 的 rbac 的方式:

public function actionUpdate($id)
{
    $model = $this->findModel($id);

    if (\Yii::$app->user->can('update', ['model' => $model])) {




        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
}

但是,当我尝试编辑 Post:

Getting unknown property: app\models\Post::createdBy

所以我想我必须用 userId 替换 createdBy,它是 table Post 中的一列,我得到一个空白页,这意味着它不起作用。所以我想猜测 $user 是什么。

我也试过:

return isset($params['model']) ? $params['model']->userId == $user->id : false;

我得到:Trying to get property of non-object.

我应该怎么做才能让它发挥作用?该文档似乎建议您只需将条件插入控制器操作中即可使其工作,但事实并非如此。

变量转储:

object(app\models\Post)[75]
  private '_attributes' (yii\db\BaseActiveRecord) => 
    array (size=6)
      'id' => int 1
      'userId' => int 1
      'title' => string 'test' (length=4)
      'content' => string 'lol' (length=3)
      'dateCreated' => null
      'dateUpdated' => null
  private '_oldAttributes' (yii\db\BaseActiveRecord) => 
    array (size=6)
      'id' => int 1
      'userId' => int 1
      'title' => string 'test' (length=4)
      'content' => string 'lol' (length=3)
      'dateCreated' => null
      'dateUpdated' => null
  private '_related' (yii\db\BaseActiveRecord) => 
    array (size=0)
      empty
  private '_errors' (yii\base\Model) => null
  private '_validators' (yii\base\Model) => null
  private '_scenario' (yii\base\Model) => string 'default' (length=7)
  private '_events' (yii\base\Component) => 
    array (size=0)
      empty
  private '_behaviors' (yii\base\Component) => 
    array (size=0)
      empty

null

第一个错误表明,您的 Post 模型中没有 createdBy 属性。你呢?

第二个错误是关于试图获取 属性 of non-object 变量。你能在 return 之前显示 var_dump($params['model']); var_dump($user); 吗?