Search code examples
symfonydoctrinemany-to-manydql

Symfony 2 fetch data from many to many relationship with doctrine


I'm stuck on getting this to work with Symfony2 and Doctrine, the situation: A page with piercing info (general info and caretaking info).

A care taking can have multiple piercings to which it applies and a piercing can have multiple care takings

Database layout:

Piercings:
    id
    name
    ...

Caretaking:
    id
    title
    description

piercing_to_caretaking
    id
    piercing_id
    caretaking_id

Now, how would I create the Entity and the corresponding Query/Dql ?


Solution

  • If you are defining your entities using yml:

    In Piercing.orm.yml add:

    manyToMany:
        caretakings:
            targetEntity: Caretaking
            inversedBy: piercings
            joinTable:
                name: piercing_caretaking
                joinColumns:
                    caretaking:
                        referencedColumnName: id
                inverseJoinColumns:
                    piercing:
                        referencedColumnName: id
    

    In Caretaking.orm.yml add:

    manyToMany:
        piercings:
          targetEntity: Piercing
          mappedBy: caretakings
    

    Generate/update the entities in the usual way, i.e.:

    app/console doctrine:schema:update --dump-sql (to check results)
    app/console doctrine:schema:update --force (to apply changes)
    

    Then when you have a Piercing or Caretaking entity you can access the related entities like this:

    $piercing->addCaretaking($caretaking); 
    $caretakings = $piercing->getCaretakings();
    ...
    $piercings = $caretaking->getPiercings();
    

    For more information, including how to do this using annotations, see sub-section 5.1.4 Many to Many, Bidirectional in Section 5 Association Mapping of the Doctrine documentation.