Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kmunky's avatar

Relationships between three tables

I have 3 models : patients, files, doctors

each patient can have multiple files. ( one for each hospital admission ) Each patient can have multiple doctors through files ( at each hospital admission, patient can have a different doctor )

Each file can have just one doctor and just one patient ( each file is created at hospital admission. Each doctor can have multiple patients and multiple files ( all his patients files ) how can i write the relations between these three models?

The tricky part is that a patient can have multiple files but a file a single patient so how can i write the reverse of the relation? Patient hasMany file, but the reverse will be something like file hasOne patient. Is that possible?

0 likes
2 replies
binalfew's avatar

@kmunky You can use:


//-------------- Patient Model Class----------
class Patient extends Model {

    public function files()
    {
        return $this->hasMany('App\File');
    }

}
//-------------- File Model Class----------
class File extends Model {

    public function patient()
    {
        return $this->belongsTo('App\Patient');
    }
}

1 like
mstnorris's avatar
Level 55

@kmunky This isn't tested but should get you going.

Patient model

public function files() {
    return $this->hasMany('App\File');
}

public function doctors() {
    return $this->hasManyThrough('App\Doctor', 'App\Patient');
}

Doctor model

public function patients() {
    return $this->hasMany('App\File');
}

public function files() {
    return $this->hasManyThrough('App\Doctor', 'App\Patient');
}

File model

public function doctor() {
    return $this->hasOne('App\Doctor');
}

public function patient() {
    return $this->belongsTo('App\Patient');
}

Check out the docs on Has Many Through and Eloquent Relationships in general.

1 like

Please or to participate in this conversation.