Yii2:创建 post 时添加 'user_id'

Yii2: Add 'user_id' when create a post

我有一个带有属性 'user_id' 的 'post' table 来知道谁 post 编辑了那个 post。我 运行 遇到了问题,当创建 post 时, 'user_id' 没有添加到数据库中,它不能为空,所以我无法从那里继续。那么如何自动添加当前登录用户的'user_id'。

我正在使用 Yii2 基本模板。

谢谢

你可以试试这个代码

//获取整个登录的用户数据

$user = \Yii::$app->user->identity;

//获取登录用户的id

$userId = \Yii::$app->user->identity->id

查看文档了解更多详情:doc .

除了Bloodhound的建议,您还可以使用以下代码获取当前登录的用户ID:

$loggedInUserId = \Yii::$app->user->getId();

或者你可以看看 Blameable Behavior

BlameableBehavior automatically fills the specified attributes with the current user ID.

我在我的很多项目中使用它(通常与 sluggabletimeable 结合使用)并且它易于使用,只需将以下内容放入您的 Post 模型中:

use yii\behaviors\BlameableBehavior;

public function behaviors()
{
    return [
        [
            'class' => BlameableBehavior::className(),
            'createdByAttribute' => 'user_id',
            'updatedByAttribute' => false,
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_VALIDATE => ['user_id'] // If usr_id is required
            ]
        ],
    ];
}

参考 验证行为。

如果你想像其他答案建议的那样手动完成,你需要改变

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

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        $model->user_id = \Yii::$app->user->identity->id
        $model->save()
        return $this->redirect(['view', 'id' => $model->id]);
    }

记住:当您在输入用户ID之前进行验证时,您的模型规则中不能要求user_id!