Jocelyn
Jocelyn

Reputation: 297

Symfony doctrine manyToOne relationship with a composite id

In a Symfony2 app, I have two entites: Club and Member.

I have to use a composite primary keys with four specific fields (edition, distance, district and id). Here is the ORM yml. The Club schema is correctly generated.

MyBundle\Entity\Club:
    type: entity
    oneToMany:
        members:
            targetEntity: Member
            mappedBy: club
    table: null
    id:
        edition:
            type: string
            length: 4
        distance:
            type: string
            length: 1
        district:
            type: integer
        id:
            type: integer
    fields:
        name:
            type: string
            length: 255
        location:
            type: string
            length: 255
    lifecycleCallbacks: {  }

My problem is now to link the Member entity. Here is my current ORM yml:

MyBundle\Entity\Member:
    type: entity
    manyToOne:
        club:
            targetEntity: Club
            inversedBy: members
            joinColumn:
                name: club_id
                referencedColumnName: ??? What if composite PK ???
    table: null
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        lastname:
            type: string
            length: 255
        firstname:
            type: string
            length: 255
        ...

What to set as referencedColumnName? How to set up the reference with a composite FK?

EDIT

I found that is possible to set multiple join colums with annotation @joinColumns{@joinColumn...@joinColumn...}. Something similar for yml configuration? I can't find any example.

Upvotes: 1

Views: 1421

Answers (1)

caponica
caponica

Reputation: 3958

Try something like this, I think it's the correct YML syntax:

manyToOne:
  club:
    targetEntity: Club
    inversedBy: members
    joinColumns:
      - joinColumn:
        name:                 club_id
        referencedColumnName: id
      - joinColumn:
        name:                 club_edition
        referencedColumnName: edition
      - joinColumn:
        name:                 club_distance
        referencedColumnName: distance
      - joinColumn:
        name:                 club_district
        referencedColumnName: district

(However, for your continued sanity, I'd strongly recommend trying to avoid composite keys where possible!)

Upvotes: 0

Related Questions