Laravel5.1查询关系(口才ORM) [英] Laravel5.1 query relationships(Eloquent ORM)

查看:69
本文介绍了Laravel5.1查询关系(口才ORM)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型是Patient-> Sample-> Ready_Sample,关系都是oneToMany, 我的问题是我查询Ready_Sample需要知道Patient.name

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

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

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

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中

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

在Sample中,我知道要获取Patient.name,但是Ready_Sample如何获取Patien.name?

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

推荐答案

您可以使用以下代码获取patient.name:

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

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

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

希望有帮助!

这篇关于Laravel5.1查询关系(口才ORM)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆