Last active
May 16, 2017 22:05
-
-
Save paulofreitas/96f266ee4e5d71bc08daf2d24ff821c2 to your computer and use it in GitHub Desktop.
Self-relationships through pivot tables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Notifications\Notifiable; | |
use Illuminate\Foundation\Auth\User as Authenticatable; | |
class User extends Authenticatable | |
{ | |
use Notifiable; | |
/** | |
* The attributes that are mass assignable. | |
* | |
* @var array | |
*/ | |
protected $fillable = [ | |
'name', 'email', 'password', | |
]; | |
/** | |
* The attributes that should be hidden for arrays. | |
* | |
* @var array | |
*/ | |
protected $hidden = [ | |
'password', 'remember_token', | |
]; | |
/* | |
* Users who this user is a doctor | |
*/ | |
public function patients() | |
{ | |
return $this->belongsToMany( | |
User::class, | |
'user_relationships', | |
'doctor_id', | |
'patient_id' | |
); | |
} | |
/* | |
* Users who are doctors of this user | |
*/ | |
public function doctors() | |
{ | |
return $this->belongsToMany( | |
User::class, | |
'user_relationships', | |
'patient_id', | |
'doctor_id' | |
); | |
} | |
/* | |
* All users who are doctors | |
*/ | |
public function scopeFilterByDoctors($query) | |
{ | |
$query->has('patients'); | |
} | |
/* | |
* All users who are patients | |
*/ | |
public function scopeFilterByPatients($query) | |
{ | |
$query->has('doctors'); | |
} | |
} | |
// All users who are doctors | |
User::filterByDoctors()->get(); | |
// All users who are patients | |
User::filterByPatients()->get(); | |
// Patients of a given user | |
User::find($id)->patients()->get(); | |
// Doctors of a given user | |
User::find($id)->doctors()->get(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment