M
M
Michael2017-04-12 03:45:43
Yii
Michael, 2017-04-12 03:45:43

What is the correct way to add a user id to a Yii2 request?

Good afternoon, a trivial question arose.
On the example of a blog
There is a table of posts as an example, there are related tables user and posts
How to automatically record the id of the current user in posts.id_user?

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

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mi7teR, 2017-04-12
@mix_gorbachev

add
an example line after the model definition:

public function actionCreate()
    {
        $model = new Post();
        $model->id_user = Yii::$app->user->identity->id;
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

E
Evgeny Bukharev, 2017-04-12
@evgenybuckharev

If user and posts are related, then it is more correct to use the link() method
https://github.com/yiisoft/yii2/blob/master/docs/g...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question