Search code examples
symfonydoctrine-orm

How to map a table to itself in Doctrine ORM using a self referencing relationship.


There is a User class which has two types of users such as patient and doctor. So, I created another attribute that is used to describe the relation between patient and doctor, a doctor can have many patients. So, If the user is patent, he should have doctorId, if not, the doctorId is NULL.

Here is my User.orm.yml:

Acme\Bundle\DemoBundle\Entity\User:
    type: entity
    table: User
    id:
        id:
            type: integer
            generator: { strategy: AUTO }
    fields:
        name:
            type: string
            length: 30
        lastName:
            type: string
            length: 30
        email:
            type: string
            length: 60
            unique: true
        username:
            type: string
            length: 10
            unique: true
        password:
            type: string
            length: 100
            unique: false
        doctorId:
            type: integer
            unique: false
            nullable: true
        dateCreated:
            type: datetime
    manyToMany:
        roles:
            targetEntity: Role
            mappedBy: users

How can I map the doctorId as a foreign key that refers to the id?


Solution

  • You can find instructions for self-referencing One-To-Many relations in the Doctrine documentation:

    User:
      type: entity
      oneToMany:
        patients
          targetEntity: User
          mappedBy:     doctor
      manyToOne:
        doctor:
          targetEntity: User
          inversedBy:   patients
    

    https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-self-referencing