Anton
Anton

Reputation: 1

Doctrine2: Many-to-One delete relations on update

I have a software which can own many screenshots.

This is the software class:

class Software
{
   public function __construct()
   {
       $this->screenshots = new ArrayCollection();
   }

   /**
    * @ORM\OneToMany(targetEntity="Screenshot", mappedBy="software", cascade={"persist"})
    * @ORM\OrderBy({"sequence" = "ASC", "id" = "ASC"})
    */
   private $screenshots;


   public function setScreenshots($screenshots)
   {
       $this->screenshots = $screenshots;
   }
}

And this is the screenshot class:

class Screenshot
{
   /**
    * @ORM\ManyToOne(targetEntity="Software", inversedBy="screenshots")
    * @ORM\JoinColumn(name="software_id", referencedColumnName="id")
    */
   private $software;

   /**
    * @param mixed $software
    */
   public function setSoftware($software)
   {
       $this->software = $software;
   }

When I generate a few new screenshots, put them into a array collection and call $software->setScreenshots($newScreenshots) with new screenshots everything works fine. The new screenshots are saved and they have the reference to the software.

But when I generate some other screenshots and call the method again, it doesn't delete the old screenshots. The new screenshots are just added.

Is there a way to have some kind of cascade option so the old screenshots are deleted? Or at least remove the reference to the software?

Upvotes: 0

Views: 1581

Answers (2)

jamek
jamek

Reputation: 812

You can let de database do the job (DBAL side):

user:
        targetEntity: User
        inversedBy: points
        joinColumn:
            name: user_id
            referencedColumnName: id
            onDelete: 'cascade' #this is important for u
        fetch: EAGER

Upvotes: 1

Jovan Perovic
Jovan Perovic

Reputation: 20193

The simplest solution would be to remove them manually:

foreach ( $software->getScreenshots() as $scrshot){
    $em->remove($scrshot);
}
$software->setScreenshots($newScreenshots);

But, apart from this solution have you tried defining orphanRemoval on inverse side or relation? Maybe that would help, but I am not sure:

/**
 * @ORM\OneToMany(targetEntity="Screenshot", mappedBy="software", cascade={"persist"}, orphanRemoval=true)
 * @ORM\OrderBy({"sequence" = "ASC", "id" = "ASC"})
 */
private $screenshots;

Upvotes: 0

Related Questions