I have a database table containing partitions. I have another table containing people. As expected, the department contains many people, and the person is in the same department.
When I want to save a new person in the database, I create a Person object and try to set its Department property to an existing one , which is managed by the Entity Manager. However, when I try to save my new Person, I get an exception:
A new object was found through the relationship "Entities \ Person # department", which was not configured to cascade the saved operations for the object: Entities \ Department @ 0000000016abe202000000000d29dd37. To solve this problem issue: either explicitly call EntityManager # persist () for this unknown entity or cascade configuration that saves this association in the mapping, for example, @ManyToOne (.., cascade = {"persist"}).
I don’t quite understand the part of the exception, which says that the department is an “unknown object”, since I extracted it through the Entity manager.
As the exception shows, I inserted the cascade into the yml metadata ( cascade: ["persist"] ). Then my person will be saved, but in the end I get a duplicated department in the department table with a new identifier.
This should be a very common use case. I have included my code and metadata below. What changes should I make?
Metadata:
Entities\Person type: entity table: people fields: ... departmentId: type: integer unsigned: false nullable: false column: department_id ... manyToOne: department: targetEntity: Entities\Department joinColumn: department_id referenceColumnName: id
the code:
$department = $em->getRepository('Department')->findOneBy(array('name' => $departmentName); $person = new Person(); $person->setName('Joe Bloggs'); $person->setDepartment($department); $em->persist($person); $em->flush();
Michael
source share