Answer the question
In order to leave comments, you need to log in
How to properly save relationships in Yii2?
there is a usual dependency between the comment, post, user tables,
this is how a new comment is added, on the backend
protected function newComment($post) {
$model = new Comment();
if ( $model->load( Yii::$app->request->post() ) ) {
$model->user_id = \Yii::$app->user->identity->id;
$model->post_id = $post->id;
$model->date = date('Y-m-d H:i:s');
$model->save();
}
return $model;
}
$comment->setPost($post);
$comment->setUser($user);
Answer the question
In order to leave comments, you need to log in
There are no direct methods, so you can implement them yourself this way
class Comment extends CActiveRecord
{
public function setUser(\User $user = null)
{
if (is_null($user))
{
$this->user_id = null;
} else
{
$this->user_id = $user->id;
}
}
}
$comment = new Comment;
$comment->user = $user;
// или
$comment->setUser($user);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question