lvarayut
lvarayut

Reputation: 15349

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?

Upvotes: 0

Views: 4372

Answers (2)

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52513

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

Upvotes: 4

Jeremy Quinton
Jeremy Quinton

Reputation: 686

With doctrine you might want to take a look at association mapping. http://docs.doctrine-project.org/en/latest/reference/association-mapping.html. In your case you are after a one to many self referencing relationship http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#one-to-many-self-referencing.

A doctor can have many patients but can a patient have many doctors? If so you have a many to many relationship which you could map out using a cross Reference table as the joining table. The best way to model this I feel is to have a userTypeId in your users Table where a value of 1 could be doctor, 2 a patient etc. Then a doctor can have many patients but also a patient can see many doctors. This would also be extensible if you added new user types like nurses etc.

Upvotes: 1

Related Questions