【问题标题】:How to save current user_id to database (YII2)如何将当前 user_id 保存到数据库(YII2)
【发布时间】:2016-11-07 02:06:03
【问题描述】:

我尝试将当前 user_id 保存到数据库中的教育表中。但是,user_id 的数据没有填写。这是我的代码。

在模型中

public function rules()
{
    return [
        [['year', 'fieldstudy', 'institute', 'grade'], 'required'],
        [['user_id'], 'integer'],
        [['year', 'fieldstudy', 'institute', 'grade'], 'string', 'max' => 255],
    ];
}


public function attributeLabels()
{
    return [
        'education_id' => 'Education ID',
        'user_id' => 'User ID',
        'year' => 'Year',
        'fieldstudy' => 'Fieldstudy',
        'institute' => 'Institute',
        'grade' => 'Grade',
    ];
}

public function getUser()
{
    return $this->hasOne(User::className(), ['user_id' => 'user_id']);
}      

在控制器处

     public function actionCreate()
{
    $model = new Education();
    $model->user_id =Yii::$app->user->id;

    if ($model->load(Yii::$app->request->post()) && $model->save()) {

        return $this->redirect(['view', 'id' => $model->education_id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

如何解决我的问题并修复我的代码?谢谢

【问题讨论】:

  • 试试 Yii::$app->user->user_id
  • 新的 Educatiion 实例保存在 db 中,但没有正确的 user_id 代码或没有保存?

标签: yii2 yii2-advanced-app yii2-user


【解决方案1】:

Yii::$app->user->id 更新为Yii::$app->user->identity->id

public function actionCreate()
    {
        $model = new Education();

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

【讨论】:

  • user_id 列的值仍为 0。@jithin
  • 它进入空白页..@jithin
  • @Fyp16 你现在可以试试吗
  • 我试过了。列 user_id 仍为 0。
【解决方案2】:

你必须检查两件事

  1. 检查用户是否登录。
  2. 使用Yii2调试器查看我们是否通过代码Yii::$app->user->idYii::$app->user->id获取登录用户的id值

使用 Yii2 调试器检查我们使用代码得到的用户 id 值是否正确

Yii::info("User id=".Yii::$app->user->id); 

您必须在控制器中尝试的完整代码如下所示

 public function actionCreate() {
        $model = new Education();

        //checking whether we are getting the logged in user id value
        Yii::info("User id=".Yii::$app->user->id); 

        $model->user_id = Yii::$app->user->id;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

             //checking here the saved user id value in  table
             Yii::info("checking User id after saving model=".$model->user_id); 

            return $this->redirect(['view', 'id' => $model->education_id]);
        } else {
            return $this->render('create', [
                        'model' => $model,
            ]);
        }
    }

现在运行应用程序后,您可以使用 Yii2 调试器检查在不同位置的用户 ID 中设置的值。

【讨论】:

  • 列 user_id 仍为 0 @ajith
猜你喜欢
  • 2018-08-11
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
相关资源
最近更新 更多