Answer the question
In order to leave comments, you need to log in
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
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,
]);
}
}
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 questionAsk a Question
731 491 924 answers to any question