-
-
Save andriesss/4233452 to your computer and use it in GitHub Desktop.
<?php | |
$user = new User(); | |
$user->addComment(new Comment('foo')); | |
$user->addComment(new Comment('baz')); | |
$user->addComment(new Comment('bar')); | |
$em->persist($user); // i only want the "user" object to be persisted, not the whole object graph | |
$em->flush(); |
However, with cascade persist, I get the following error:
Entity of type Comment has identity through a foreign entity User, however this entity has no identity itself. You have to call EntityManager#persist() on the related entity and make sure that an identifier was generated before trying to persist 'Comment'. In case of Post Insert ID Generation (such as MySQL Auto-Increment or PostgreSQL SERIAL) this means you have to call EntityManager#flush() between both persist operations.
So the only option I seem to have is to do:
$user = new User();
$em->persist($user);
$em->flush();
$user->addComment(new Comment('foo'));
$user->addComment(new Comment('baz'));
$user->addComment(new Comment('bar'));
$em->persist($user);
$em->flush();
... but I don't want that?
I need the comment entity here, otherwise no help possible
I simplified the example, so it wasn't actually code I was using. The entities would be something like this:
<?php
/** @Entity */
class User
{
/** @Id @GeneratedValue @Column(type="integer") */
private $id;
/**
* Bidirectional - One-To-Many (INVERSE SIDE)
*
* @OneToMany(targetEntity="Comment", mappedBy="author")
*/
private $commentsAuthored;
public function __construct()
{
$this->commentsAuthored = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addComment(Comment $comment)
{
$comment->setAuthor($this);
$this->commentsAuthored[] = $comment;
return $this;
}
}
/** @Entity */
class Comment
{
/** @Id @GeneratedValue @Column(type="integer") */
private $id;
/**
* Bidirectional - Many Comments are authored by one user (OWNING SIDE)
*
* @ManyToOne(targetEntity="User", inversedBy="commentsAuthored")
*/
private $author;
/**
* @var string
*/
private $value;
public function __constuct($value)
{
$this->value = $value;
}
public function setAuthor(User $user)
{
$this->author = $user;
return $this;
}
}
cascade persist on User#comments will work here
It results in the error of comment #2
but comment doesnt have identity through a foreign entity, it has its own ID field with auto generated value. You must show the wrong code, you cannot get that error message.
I think you've just answered my question. In "the real code", the entity has identity through a foreign entity.
I have the same problem, did you find a solution to the problem?
New entities in a collection not marked as cascade persist will produce an Exception and rollback the flush() operation.