Laravel5.1 query relationships(Eloquent ORM)

2019-08-06 00:44发布

My model is Patient->Sample->Ready_Sample ,relationship all is oneToMany , My question is I query Ready_Sample need to know patient.name

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');
    }
}

In 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;
}

In Sample I know to get patient.name ,but Ready_Sample how to get Patien.name?

1条回答
够拽才男人
2楼-- · 2019-08-06 00:56

You can get the patient.name using the below code:

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

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

Hope it helps!

查看更多
登录 后发表回答