Search code examples
phpormdoctrine-ormsymfony-2.3

Symfony 2 - How to set relationship between three entities having many to many relationship among them


I am using Symfony2 for my application and using Doctrine .orm.yml files for relation mapping.

I have three entities as follows:

  1. user entity which contains id(integer primary key), user_name(varchar)

  2. portfolio entity which contains id(integer primary key), name(varchar), user_id (FK from user to identify who created the portfolio)

  3. progress entity which contains id(integer primary key), progress_text(varchar)

My problem is that I am not aware how to set the many to many relationship among three entities i.e. Portfolio, User and Progress.

I want to set a relationship in a way such that the new table that gets created as a result of this relationship contains the below fields:

  1. user_id
  2. portfolio_id
  3. progress_id
  4. created_at
  5. updated_at
  6. type

In the above list created_at, updated_at and type are the fields that I am using for some business rules purpose.

Please some body help me in writing their .orm.yml files. I understand that there are inbuilt commands in Symfony2 that generates entity and their corresponding .orm.yml files. But I am not aware how to write the above required relation in their corresponding file.


Solution

  • You need to create separate association table for this relationship. Your ORM file will be like:

    
    Application\Bundle\Entity\nameofAssociationTable:
      type: entity
      table: nameofAssociationTable
      fields:
        id:
          type: integer
          id: true
          generator:
            strategy: AUTO
      manyToOne:
    user:
          targetEntity: Application\Bundle\Entity\User
          cascade: {  }
          mappedBy: null
          inversedBy: null
          joinColumns:
            user_id:
              referencedColumnName: id
          orphanRemoval: false
    portfolio:
          targetEntity: Application\PLibBundle\Entity\Portfolio
          cascade:
            - persist
            - remove
          mappedBy: null
          inversedBy: null
          joinColumns:
            portfolio_id:
              referencedColumnName: id
          orphanRemoval: false
      lifecycleCallbacks: {  }
     

    Likewise you need add relation into manytoOne relationship. Thanks.