I have a very basic schema like this:
Comments.yml:
manyToOne:
pages:
targetEntity: Pages
inversedBy: comments
joinColumn:
name: page_id
referencedColumnName: idx
... other things ...
Pages.yml:
oneToMany:
comments:
targetEntity: Comments
mappedBy: pages
cascade: ["persist"] // i added this later but has no effect for both persist and merge.
orderBy:
idx: desc
... other things ...
Now, everything is working just fine. I can get Pages from Comments and reverse. The problem is, when i try to insert a new row to the database, it says page_id is null.
Example:
$comment = new Comments();
$comment->setPageId(2); // it is "2"
$comment->setText($textData);
$this->_em->persist($comment);
$this->_em->flush($comment);
Now the result is false. It throws an exception and says SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "page_id" violates not-null constraint.
Well, if i remove the oneToMany and ManyToOne relations, it works! If i use them it says it is null even if i give it…
Where is my mistake? Any help or idea is appreciated!
EDIT:
I found this method: getReference()
$item = $em->getReference('MyProject\Model\Item', $itemId);
$cart->setPage($item);
Now it is working but i do not know if this is the correct way. Please inlight me.
Basically, i want to add a comment without modifying (not remove nor update) the page table. But, i want to fetch them together as ManyToOne and OneToMany.
When You want to add a page to the Comments entity You should call a method like
$comment->setPage($page)this method is automatically generated if you use thephp app/console doctrine:generate:entitiescommand line. The $page object should be the $page object loaded from the database. e.g.If this doesn’t help You, please post your code from your controller and the pages and comments entity.