1、when() 方法使用
$region = $user["region"];
$date = date('Y-m-d 00:00:00',time());
$data = Patient::where(function ($query) use($date) {
$query->where("patients.created_at",">",$date)
->orWhere("patients.first_dosage_time",">",$date);
})
// ->where("patients.region_id",$region)
->when($region != 0 , function ($query) use ($region) {
return $query->where("patients.region_id",$region);
})
->select('patients.id','prefectures.prefecture_name','deputies.deputy_name','patients.city','hospitals.code','hospitals.hospital_name','patients.name','patients.phone','patients.type','patients.is_inspect','patients.inspect_channel','patients.inspect_result','patients.other_type','patients.is_recommend','patients.doctor','patients.department','patients.is_conversion','patients.dosage_time','patients.first_dosage_num','patients.oral_dose','patients.now_dosage_time','patients.now_dosage_num','patients.is_united_bevar','patients.payment_method','patients.medical_insurance_city','patients.next_dosage_time','patients.next_dosage_num','patients.fall_off','patients.fall_off_cause','patients.fall_off_time',"region_name")
->leftJoin("hospitals","hospitals.id","=","patients.hospital_id")
->leftJoin("deputies","deputies.id","=","patients.deputy_id")
->leftJoin("prefectures","prefectures.id","=","patients.prefecture_id")
->leftJoin("regions","regions.id","=","patients.region_id")
->orderBy("patients.region_id","asc")
->get();
2、with()使用一: 使用匿名函数
$patientList = Patient::when($region != 0,function ($query) use ($region){
return $query->where("region_id",$region);
})
->select("id","region_id","name","phone","deputy_id","created_at","dosage_time","next_dosage_time","fall_off","other_type","uniqucode","doctor","department","type","first_dosage_num","oral_dose","city","next_dosage_num")
// padeputy 方法通过deputy_id代表Id跟代表表进行一对一关联.
->with(['padeputy' => function($query){
return $query->select("id","deputy_name","abb");
}])
//paregion 方法通过region_id 区域ID跟区域表进行一对一关联.
->with(['paregion' => function($query){
return $query->select("id","region_name");
}])->get();
3、with()使用二:
控制器代码
$hospitalRecords = HospitalRecord::withTrashed()
->with(['patient','cancer_category'])
->filter($filter)
->paginate();
模型代码
public function patient()
{
return $this->belongsTo(
Patient::class,
'patient_id',
'id'
);
}
public function cancer_category()
{
return $this->belongsTo(
CancerCategory::class,
'category_id',
'id'
);
}