B
B
badicean2015-10-02 20:22:44
MySQL
badicean, 2015-10-02 20:22:44

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;
    }

I feel that it is possible to make it more beautiful, since the connections are registered. something like
$comment->setPost($post);
$comment->setUser($user);

how can you bypass all these direct field calls ($model->user_id, $model->post_id) ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Volintsev, 2015-10-02
@copist

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);

In fact, the scheme is much more complicated than just writing a setter for the user property.
What to do if you change the user_id property through which the user is calculated - it seems like it needs to be loaded from the database again?
Will the $user entities be identical for two different comments with the same user_id?
What if $user hasn't been saved yet? Don't allow $comment->setUser($user) to be assigned or do automatic saving in a chain (first $user, then $comment) ?
Many many many questions.
In Yii2, such complexities are not implemented, since a universal all-encompassing solution like in Doctrina or PropelORM is very slow and eats up memory. There just sometimes it is necessary to prohibit fancy logic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question