Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lologhi/220fe7dfbc92ec858a33 to your computer and use it in GitHub Desktop.
Save lologhi/220fe7dfbc92ec858a33 to your computer and use it in GitHub Desktop.
Apply fixtures on Doctrine entities with ManyToMany relations

Club entity

/**
 * @ORM\ManyToMany(targetEntity="Field", inversedBy="clubs")
 */
private $fields;

Field entity

/**
 * @ORM\ManyToMany(targetEntity="Club", mappedBy="fields")
 */
private $clubs;

The command php app/console doctrine:schema:update will create a club_field table

In the fixtures :

$club->addField($this->getReference('field'.$field));

will be possible because of the order of the relation. To do

$field->addClub($this->getReference('club'.$club));

you might have to reverse the relations in the entities, so that the relation table is field_club.

@Remiii
Copy link

Remiii commented Dec 13, 2014

You can do the same with field_club and club_field...

Just add cascade={"persist","remove"} in annotation of fields and clubs and update addField and addClub with something like this:

    /**
     * Add fields
     *
     * @param \remiii\GlobalBundle\Entity\Field $fields
     * @return Club
     */
    public function addField(\remiii\GlobalBundle\Entity\Field $fields)
    {
        $this->fileds[] = $fields;
        $fields -> addClub ( $this ) ;

        return $this;
    }
    /**
     * Add clubs
     *
     * @param \remiii\GlobalBundle\Entity\Club $clubs
     * @return Field
     */
    public function addClub(\remiii\GlobalBundle\Entity\Club $clubs)
    {
        $this->clubs[] = $clubs;
        $clubs -> addField ( $this ) ;

        return $this;
    }

Off course setReference and getReference are your friends and getOrder must be set in Fixtures.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment