Skip to content

Instantly share code, notes, and snippets.

@andriesss
Created December 7, 2012 14:03
Show Gist options
  • Save andriesss/4233452 to your computer and use it in GitHub Desktop.
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();
@andriesss
Copy link
Author

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;
    }
}

@beberlei
Copy link

beberlei commented Dec 7, 2012

cascade persist on User#comments will work here

@andriesss
Copy link
Author

It results in the error of comment #2

@beberlei
Copy link

beberlei commented Dec 7, 2012

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.

@andriesss
Copy link
Author

I think you've just answered my question. In "the real code", the entity has identity through a foreign entity.

@mghazal
Copy link

mghazal commented May 30, 2014

I have the same problem, did you find a solution to the problem?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment