2015-10-08 82 views
1

我的模型是患者 - >的Sample-> Ready_Sample,關係都是一對多, 我的問題是我查詢Ready_Sample需要知道patient.nameLaravel5.1查詢關係(雄辯ORM)

Patient_Model

class Patient_Model extends Base_Model { 

    protected $table = 'patients'; 

    public function samples(){ 
     return $this->hasMany('App\Models\Sample_Model','patient_id','code'); 
    } 
} 

Sample_Model

class Sample_Model extends Base_Model{ 

    protected $table = 'samples'; 

    public function patient(){ 
     return $this->belongsTo('App\Models\Patient_Model','patient_id','code'); 
    } 

    public function ready_samples(){ 
     return $this->hasMany('App\Models\Ready_Sample_Model','sample_id','code'); 
    } 
} 

Ready_Sample_Model

class Ready_Sample_Model extends Model{ 

    protected $table = 'ready_samples'; 

    public function sample(){ 
     return $this->belongsTo('App\Models\Sample_Model','sample_id','code'); 
    } 
} 

在Sample_Controller

class Sample_Controller extends Controller{ 

    public function query(Request $request){ 

    $result = Sample_Model::with(['patient']); 
     ->orderBy("updated_at","desc") 
     ->Paginate(15) 
     ->toJson(); 
    return $result; 
} 

在樣品我知道拿到patient.name,但Ready_Sample如何獲得Patien.name?

回答

0

您可以通過下面的代碼獲得patient.name

$readySample = Ready_Sample_Model::first(); // fetch the first record 

echo $readySample->sample->patient->name; 

希望它能幫助!

+0

謝謝,但我有很多這種關係。例如:patient-> sample-> ready_saple-> xxx-> xxx-> xxx-> xxx-> demo,但是演示我也得到了一個patient.name。我應該寫關係的行代碼?.... –