Symfony 3.4 を使って記事とコメントを登録できる機能を作っています。
記事に対して複数のコメントをまとめてセットする関数を作ろうとしているのですが意図したように動作しません。
1記事に複数のコメントを付けられる構造で、エンティティは次のようになっています。(部分)
php
1class Article 2{ 3 /** 4 * @ORM\OneToMany(targetEntity="Comment", mappedBy="article", cascade={"persist"}, orphanRemoval=true) 5 */ 6 private $comments; 7 8 public function __construct() 9 { 10 $this->comments = new ArrayCollection(); 11 } 12 13 public function addComment($comment) 14 { 15 if(!$this->comments->contains($comment)){ 16 $comment->setArticle($this); 17 $this->comments->add($comment); 18 } 19 } 20 21 public function getComments() 22 { 23 return $this->comments; 24 } 25 26 public function setComments($comments) 27 { 28 $this->comments->clear(); 29 30 foreach($comments as $comment){ 31 $this->addComment($comment); 32 } 33 34 return $this; 35 } 36}
実験用のコントローラー
// 何らかの Comment の配列 $comments = $article->getComments()->toArray(); $newComment = new Comment(); $newComment->setMessage('example'); $comments[] = $newComment; $article->setComments($comments); $em->flush();
想定ではもともとのコメントに新しいコメントが1つ追加されるという動きだったのですが、
実際には新しく追加したコメントだけが登録されており、過去のコメントは orphanRemoval によって削除されていました。
setComments() を使って記事のコメントを配列でセットし、使われなくなったコメントのレコードは削除し、もともと紐付けられているコメントはそのままにし、追加されたコメントはデータベースに登録するという動きを作りたいのですがどのようにすればいいのでしょうか?
追記
SQLのログは次の通りです
sql
1SELECT t0.id AS id_1, t0.message AS message_2, t0.article_id AS article_id_3, t4.id AS id_5, t4.title AS title_6, t4.content AS content_7, t4.category_id AS category_id_8 FROM comments t0 LEFT JOIN article t4 ON t0.article_id = t4.id WHERE t0.article_id = 1 2 3START TRANSACTION 4 5INSERT INTO comments (message, article_id) 6VALUES 7 ("example", 1) 8 9DELETE FROM comments WHERE id = 5 10 11COMMIT
※ コメントの id = 5 はもともと登録されてあったコメントの id です
あなたの回答
tips
プレビュー