Jules R
Jules R

Reputation: 553

How to persist an entity related to an already existing one?

I have seen a lot of examples about cascading with doctrine (including the doc) but every single example is about creating eg a new user, a new comment and saving both.

In my case the post and the user already exist, not the comment.

The classes look like this: enter image description here

My question is the following: with this kind of complexe scheme, which entity should be persisted / merged and in which order when saving a comment on an existing post by an existing user ?

I don't want code, just an explanation about how it works, that's why I don't include the code. Thanks.

Upvotes: 0

Views: 72

Answers (2)

Lajos Arpad
Lajos Arpad

Reputation: 76426

You will just need to set the Author and Post and then persist the new comment:

$comment->setAuthor($yourAuthor)
        ->setPost($yourPost);
$em->persist($comment);
$em->flush();

Here I did not pay too much attention to Answers[], because you did not explain the relationship. However, if Answer is another Comment and if a Comment can be an Answer to only another Comment, then you might need adding a Replied field, which will be a Comment and essentially a foreign key, so all the comments inside Answers[] will have a Replied field, which is the Comment whose Answered[] contains the other Comment.

Upvotes: 0

iiirxs
iiirxs

Reputation: 4582

Cascading doesn't really help you in this case, since I imagine that you have a standalone (not embedded) CommentType form. So you get a Comment object in your controller which you have to persist, associated to already existing User and Post entities.

Cascading would be useful if you had a PostType form for example with an embedded CommentType form (through a comment field) and you wanted to persist (or update) both a Post and a Comment entity.

I would suggest to add a post_id field in your CommentType Form and use a DataTransformer like Symfony documentation suggests here to transform the post_id to a Post entity. Finally all you'll have to do is explicitly set your user in your controller:

...
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $comment->setUser($this->getUser());
    $em->persist($comment);
    $em->flush();
}

Upvotes: 1

Related Questions