Doctrine many to one relationship persist operation
doctrine-orm, mysql, php
Solution
You are probably persisting the story entity but not the user. If you have something like this:
$story = new Story();
$user = new User();
$story->setUser($user);
$em->persist($story);
$em->flush();
This will result in a fatal error, since you are persisting one entity, but through its relations, Doctrine finds another new entity. You have two options:
Call persist on both entities:
$story = new Story();
$user = new User();
$story->setUser($user);
$em->persist($story);
$em->persist($user);
$em->flush();
Or, set up cascading persist for the Story entity. Eg. if you are using annotation mapping, you would do something like
/**
* @ManyToOne(targetEntity="User", inversedBy="stories", cascade={"persist"})
*/
private $author;
The chapter 8. Working with associations details this.
Problem
I have a story table and user table. The column userid in story table is a foreign key which refers the id in user table. I have set the relationship is that a user may have many stories which is stored in story table. I have created the entities of both table. But if try to persist operation only to story table it is asking the details for new user entry. My objective is to add a new story with existing `userId`. Am posting the error here: A new entity was found through the relationship 'Story#_userId' that was not configured to cascade persist operations for entity: User@0000000038960c50000000008ea93852. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={\"persist\"}). I set ManyToOne relationship in `Story` entity: ``` /** * @ManyToOne(targetEntity="User", inversedBy = "_story" ) * @JoinColumns({ * @JoinColumn(name="user_id", referencedColumnName="id") * }) */ private $_userId; ``` I checked the database schema and it shows relationship is set correctly. So I have done the story insertion process. ``` $user = new User(); $user->setUserId($id); $story = new Story(); $story->setContent("...."); $story->setUserid($user); $this->em->persist($story); $this->em->flush(); ```