首页 > 解决方案 > yii2如何查看自己的实体?

问题描述

我有一个用户表,其中有一个名为“society_id”的字段,它定义了用户所属的社会。同样,我在另一个名为“expense_details”的表中有“society_id”字段,它标识了在“expense_details”中输入数据的用户的society_id。

这是我的用户表

https://i.stack.imgur.com/1hBky.png

这是我的费用明细表

https://i.stack.imgur.com/Z3cQU.png

我知道我们可以像这样访问登录用户的 social_id:

我希望登录的用户访问他们的视图,但我希望用户不要访问与更改 url 的其他用户相关的表“expense_details”中的数据。

我知道我们可以像这样 Yii::$app->user->identity->society_id 获得登录用户的 social_id 但我想知道如何在这里使用它以及我应该在我的 actionView 和/或中进行哪些更改模型。

这是我的 Expensedetails 视图控制器。

 public function actionView($id) {

    $details = \app\models\ExpenseDetails::find()->where(['expense_id' => $id])->all();
    $searchModel = new \app\models\ExpenseDetailsSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    $dataProvider->query->where("expense_id=$id");

    return $this->render('view', [
                'model' => $this->findModel($id),
                'details' => $details,
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
    ]);
}

PS:英语不是我的母语。我是 yii2 和 stackoverflow 的新手,请原谅我的错误。谢谢。

标签: yii2

解决方案


我解决了。

在我的费用详情模型中

protected function findModel($id)
{
    if (($model =ExpenseDetails::findOne($id)) !== null) {
        return $model;
    }

    throw new NotFoundHttpException('The requested page does not exist.');
}

在我的费用详情视图控制器中

protected function findModel($id)
{
    if (($model = ExpenseDetails::findOne($id)) !== null) {
        return $model;
    }

    throw new NotFoundHttpException('The requested page does not exist.');
}

推荐阅读