Jared Meyering
Jared Meyering

Reputation: 1321

Laravel relationship with multiple foreign keys

What is the standard way to set up your tables and models with table that have multiple foreign keys.

Example one foreign key relationships typicall look like

database tables:

clients
    id
    name
doctors
    id
    name
client_doctor
    client_id
    doctor_id

But for my example, a doctor also may be associated with multiple clinics, and at each clinic may have multiple types.

I want to refactor my tables to reflect laravel standards but currently my tables look like

clients
doctors
clinics
doctypes
doctor_clinic_doctype
    doctor_id
    clinic_id
    doctype_id
client_doctor_clinic_type
    client_id
    the three columns from doctor_clinic_type as a foreign key

What is best practice here.

Upvotes: 1

Views: 1194

Answers (1)

Aloys
Aloys

Reputation: 682

Since Eloquent will give pivot tables also an id column you could match on that id.

So the tables might look like this.

doctor_clinic_doctype
    id
    doctor_id
    clinic_id
    doctype_id

client_doctor_clinic_type
    client_id
    doctor_clinic_doctype_id (foreign key on doctor_clinic_doctype.id)

I think this is probably the only solution that will work well with Eloquent (not sure though).

Upvotes: 1

Related Questions