Marcel
Marcel

Reputation: 6300

Symfony2 Many-to-Many relationship sharing one JoinTable

I want to make a Many-to-Many relationship which shares the same join table. I tried the following:

<?php
/** @Entity **/
class User
{
// ...

/**
 * @ManyToMany(targetEntity="Group", inversedBy="users")
 * @JoinTable(name="users_groups")
 **/
private $groups;

// ...
}

/** @Entity **/
class Group
{
// ...
/**
 * @ManyToMany(targetEntity="User", mappedBy="groups")
 * @JoinTable(name="users_groups")
 **/
private $users;

// ...
}

This, however, returns the following error when I try to update the tables:

[Doctrine\DBAL\Schema\SchemaException]                           
  The table with name 'postgres.user_groups' already exists. 

How do I create a many-to-many relationship that shares the same table 'user_groups'?

Note: I understand that I can remove the @JoinTable(name="users_groups") but when I do this I no longer have a Many-to-Many relationship with two owning sides. Instead only one side (owning side) knows about the join table.

Upvotes: 1

Views: 1592

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

Remove @JoinTable(name="users_groups") annotation from your inverse side entity that is Group, Once owning side entity has mapping information then there is no need to define again in inverse side entity, some of the key point related to your question

The inverse side has to use the mappedBy attribute of the OneToOne, OneToMany, or ManyToMany mapping declaration. The mappedBy attribute contains the name of the association-field on the owning side.

The owning side has to use the inversedBy attribute of the OneToOne, ManyToOne, or ManyToMany mapping declaration. The inversedBy attribute contains the name of the association-field on the inverse-side.

You can pick the owning side of a many-to-many association yourself

Reference Bidirectional Associations

class Group
{

    /**
     * @ManyToMany(targetEntity="User", mappedBy="groups")
     **/
    private $users;

}

See Many-To-Many, Bidirectional example from documentation

Upvotes: 3

Related Questions