I've been trying to get a hold of a solution for this for some time now, but failed: When I try to persist a new entity in Doctrine 2.3 and flush afterwards, I receive:
CRITICAL: Doctrine\ORM\ORMInvalidArgumentException: A new entity was found through the relationship 'Task#parentTask' that was not configured to cascade persist operations for entity
I have a self-referencing entity Task that looks -- in a condensed view --like this:
class Task
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
private $id;
/**
* @ManyToOne(targetEntity="tasks\classes\Task", inversedBy="childTasks", fetch="LAZY")
* @JoinColumn(name="parent", referencedColumnName="id")
*/
private $parentTask;
/**
* @OneToMany(targetEntity="tasks\classes\Task", mappedBy="parentTask", fetch="LAZY")
*/
private $childTasks;
}
And based on this task, I'm Now I'm fetching a task using a query built in QueryBuilder:
function getTasksCreatedByUser($user)
{
$em = $this->db->getEntityManager();
$qb = $em->createQueryBuilder();
$query = $qb->select("t")
->from("tasks\classes\Task", "t")
->where($qb->expr()->andX(
"t.creator = :creator"
// plus more conditions here
))
->setParameter("creator", $user)
->orderBy("t.id", "DESC")
->getQuery()
;
return $query->getResult();
}
For each of these tasks, I create a new task referencing them as $parentTask (code shortened):
foreach($tasks as $task) {
$newTask = new \tasks\classes\Task();
$newTask->setParentTask($task);
$db->persist($newTask);
}
class DB
{
public function persist($entity)
{
$this->entityManager->persist($object);
$this->entityManager->flush();
}
}
In other parts of my application, the same pattern works fine, and I cannot find what the difference is.
Can any of you help me understand why the exception is thrown? I read through a dozen of other threads referencing the same exception, and usually it was the case that there was somehow a relationship between two objects, both not persisted so far; one would be persisted, the other not, and that would throw the exception. I cannot see that happening in my case though.
Any help is appreciated!