Tim Joseph
Tim Joseph

Reputation: 847

Doctrine: Update whole Entity

first off some code:

class User {
     * @ORM\OneToMany(targetEntity="Profile", mappedBy="user")
     */
    protected $profiles;
}

(There's come more code, but this is the part affecting my problem).

So for example I have

Already in Database

User1: id = 1
Profile1: id = 1, parent = User1
Profile2: id = 2, parent = User2

Not yet persisted

Profile3: 
Profile4: 

What I want to do is to be able to just call:

$user1->removeAllProfiles(); $user1->addAllNewProfiles(array($profile3, $profile4));

and this should automatically delete all the old profiles and add all the new.

I hope it's clear what I want to achieve. Anyone having an idea?

Upvotes: 0

Views: 95

Answers (1)

JamesHalsall
JamesHalsall

Reputation: 13505

You can update your property annotation to make use of orphanRemoval...

/** @OneToMany(targetEntity="Profile", mappedBy="user", orphanRemoval=true) */
protected $profiles;

This tells Doctrine to remove any profiles that are left without an associated User object, so when you call $user->removeAllProfiles(); and then call $em->flush() any previous Profile objects associated with the user will be removed from the database.

Upvotes: 1

Related Questions