簡體   English   中英

Laravel5.1查詢關系(口才ORM)

[英]Laravel5.1 query relationships(Eloquent ORM)

我的模型是Patient-> Sample-> Ready_Sample,關系都是oneToMany,我的問題是我查詢Ready_Sample需要知道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');
    }
}

在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?

您可以使用以下代碼獲取patient.name

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

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

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM