Move element from one collection to another

23 views
Skip to first unread message

acid24

unread,
Feb 24, 2020, 11:02:27 AM2/24/20
to doctrine-user
Hi,

I have an entity Group and an entity Member. Group to Member is a OneToMany bidirectional relationship. That makes the ManyToOne relationship defined on Member the owning side is the. My question is how can I have code that moves a member to another group. For example:

class Group
{
    
    private $id;
    private $members;
    
    public function __construct()
    {
        $this->members = new ArrayCollection();
    }

    public function moveMembersToAnotherGroup(array $ids): self
    {
        $newGroup = new self();
        
        foreach ($ids as $id) {
            $member = $this->members->get($id);
            $this->members->remove($id);
            $member->setGroup($newGroup);
        }
        
        return $newGroup;
    }
}

class Member
{
    
    private $id;
    private $group;

    public function setGroup(Group $group)
    {
        $this->group = $group;
    }
}

$group = $groupRepo->ofId(1);
$newGroup = $group->moveMembersToAnotherGroup([1, 2]);

$groupRepo->save($group);
$groupRepo->save($newGroup);


Is such a thing possible with Doctrine 2? If yes, how? 

Thanks in advance

acid24

unread,
Feb 25, 2020, 1:59:39 AM2/25/20
to doctrine-user
Also forgot to mention that the moved members have to retain their id. I managed to came close by making a copy/clone of each member I want to move and using orphanRemoval, but that reassigns new ids to the members which is not what I want. Without orphanRemoval I could only manage to have the new group created, but for some reason the reference update to the new group is not being picked up by doctrine. Does anybody have any ideas why that is? 
Reply all
Reply to author
Forward
0 new messages