0

App\Bundle\Resources\config\doctrine\User.orm.yml

App\Bundle\Entity\User:
    type:  entity
    table: Users

    // ...

    manyToMany:
        groups:
            targetEntity: Group
            inversedBy: users
            joinTable:
                name: Users_relate_Groups
                joinColumns:
                    user_id:
                        onDelete            : CASCADE
                        referencedColumnName: id
                inverseJoinColumns:
                    group_id:
                        onDelete            : CASCADE
                        referencedColumnName: id

App\Bundle\Resources\config\doctrine\Group.orm.yml

App\Bundle\Entity\Group:
    type:  entity
    table: Groups

    // ...

    manyToMany:
        users:
            cascade     : ["persist"]
            mappedBy    : groups
            targetEntity: User

App\Bundle\Entity\User.php

use FOS\UserBundle\Model\User as BaseUser;

class User extends BaseUser
{
    protected $groups;

    public function __construct()
    {
        parent::__construct();
        $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...

App\Bundle\Entity\Group.php

use FOS\UserBundle\Model\Group as BaseGroup;

class Group extends BaseGroup
{
    protected $users;

    public function __construct($name, $roles = array())
    {
        parent::__construct($name, $roles);
        $this->users = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function addUser(\App\Bundle\Entity\User $users)
    {
        if (!$this->getUsers()->contains($users)) {
            $this->getUsers()->add($users);
        }

        return $this;
    }

    public function getUsers()
    {
        return $this->users;
    }

    // ...

Now, this condition.

And this does work correctly.
A group is added to the user.

$user->addGroup($group);
$userManager->updateUser($user);

But this doesn't work.
The user isn't added to the group.

$group->addUser($this->getUser());
$groupManager->updateGroup($group);

A user can't be added from a group object.

Devatim
  • 331
  • 2
  • 10

1 Answers1

0

Often the add function will need to call the corresponding tag on the inverse side as well. There's another answer with a similar solution

This one is actually kind of tricky since it needs to work both ways. I don't think the recurse will be a problem, because the third call will be skipped since users already contains the group.

public function addUser(\App\Bundle\Entity\User $users)
{
    if (!$this->getUsers()->contains($users)) {
        $this->getUsers()->add($users);
        $users->addGroup($this);
    }

    return $this;
}

So in order:

  1. You call Group->addUser
  2. Group calls User->addGroup
  3. User (probably) calls Group->addUser
  4. Since Group already has the user, it ends.

There's probably a better solution to this, but it should at least work.

Community
  • 1
  • 1
Waddles
  • 196
  • 2
  • 7