Bawię się w sandboxie Doctrine 2.1 i chcę powiązać ze sobą odpowiednio "Entitiesy": Question i Answer. Uznałem, że relacja powinna być (patrząc od strony Question) OneToMany, bidirectional, Question po stronie Owning.
Jednak, kiedy stworzę Question i Answer, dodam Answer do Question i zapiszę Question, to zapisuje się on w bazie bez Answer:
$q = new Entities\Question; $q->setTitle('Co jest grane?'); $q->setDetails('szczegóły pytania'); $a = new Entities\Answer; $a->setText('Odpowiedź jest taka a taka.'); $q->addAnswer($a); $em->persist($q); $em->flush();
Ponadto, jak zrobię odwrotnie i dodam Question do Answera i spróbuję zapisać Answer:
$q = new Entities\Question; $q->setTitle('Co jest grane?'); $q->setDetails('szczegóły pytania'); $a = new Entities\Answer; $a->setText('Odpowiedź jest taka a taka.'); $a->setQuestion($q); $em->persist($a); $em->flush();
to dostaję błąd: InvalidArgumentException: A new entity was found through the relationship 'Entities\Answer#question' that was not configured to cascade persist operations for entity: Entities\Question@0000000006b2387700000000290a0be5. Explicitly persist the new entity or configure cascading persist operations on the relationship. If you cannot find out which entity causes the problem implement 'Entities\Question#__toString()' to get a clue. in H:\serwer\projekty\doctrine2-orm2\lib\Doctrine\ORM\UnitOfWork.php on line 576
Generalnie wygląda to dla mnie jakby Answer był po stronie Owning i jakby cascading był dobrze skonfigurowany, to by się zapisało Answer ze swoim Question...
Co zmienić, żeby powiązanie między Question a Answer działało prawidłowo? Poniżej kod omawianych Entities:
namespace Entities; class Answer { private $id; private $text; /** * @ManyToOne(targentEntity="Question", mappedBy="answers") */ private $question; public function setQuestion(\Entities\Question $question) { $this->question = $question; } public function getQuestion() { return $this->question; } }
namespace Entities; use Doctrine\Common\Collections\ArrayCollection; class Question { private $id; private $title; private $details; /** * @OneToMany(targentEntity="Answer", inversedBy="question") */ private $answers; public function __construct() { $this->answers = new ArrayCollection(); } public function addAnswer($answer) { $answer->setQuestion($this); $this->answers[] = $answer; } public function getAnswers() { return $this->answers; } }