Mient-jan Stelling
Mient-jan Stelling

Reputation: 532

Doctrine 2: bi-directional relation, Adding entity on not owning will not persist

Doctrine 2: bi-directional relation, Adding entity on not owning will not persist

class AuthRole
{
    /**
     * @ORM\OneToMany(targetEntity="AuthUser", mappedBy="role", cascade={"persist","detach"})
     * @ORM\JoinColumn(name="role_id", referencedColumnName="id")
     */
    private $authUsers;
}

AuthRole is the not owning side

class AuthUser 
{
    /**
    * @ORM\ManyToOne(targetEntity="AuthRole", inversedBy="authUsers", cascade={"persist","detach"})
    * @ORM\JoinColumn(name="role_id", referencedColumnName="id")
    */
    private $role;
}

AuthUser is the owning side

if i add a user to the role the relation will not be saved and AuthUser->role is null; Why is this and is this fixable.

i know that when you add a role to the user the relation is saved but thats not what i want.

Upvotes: 2

Views: 526

Answers (1)

Lusitanian
Lusitanian

Reputation: 11122

Modify your addUser function under the AuthRole entity:

public function addAuthUser(AuthUser $authUser)
{
  $authUser->setAuthRole($this); // important line
  $this->authUsers[] = $authUser;
}

If you use a setter, then loop over the entire array and call setAuthRole($this) on each.

Upvotes: 2

Related Questions