我需要限制只有自己的用户可以在 yii2 中更新和查看他的记录。此外,其他用户无法通过更改 URL 中的记录 ID 来更新和查看其他用户实体。
执行此操作的最佳方法是通过 RBAC 您在此处查看教程:
https://www.youtube.com/watch?v=eFOIUeU-Y74
https://www.youtube.com/watch?v=G9-tBshv3Uo
否则,您可以通过在模型和视图中放置 if 条件来做到这一点
即
您的表必须具有owner_id
字段,该字段将包含实体的所有者 ID。
然后,您可以在模型中覆盖find()
方法,即
public static function find()
{
$find = parent::find();
// filter all records by loggedin id with owner_id match
$find->andWhere(['owner_id' => Yii::$app->user->identity->id]);
return $find;
}
在控制器中,您可以放置 if 条件,例如:
public function actionView($id)
{
$model = $this->findModel($id);
if($model->owner_id != Yii::$app->user->identity->id) {
throw new yiiwebForbiddenHttpException;
}
return $this->render('view', [
'model' => $model,
]);
}