Laravel Join 查询不适用于 4 个表

我有 4 张桌子


表名称:诊所


字段:诊所ID,诊所名称


表名:位置


归档:位置 ID、诊所 ID、位置名称


表名:服务


字段:ServiceId、ServiceName


表名:LocationServices


字段:locationServiceID、locationID、ServiceId


我的要求是,当我通过 ClinicID 时,我需要检索相应的诊所服务名称,可能不止一个。


但是当我尝试加入查询时不起作用以下是我在控制器中的代码


 public function showClinic($id)

    {

        $clinic = Clinic::find($id);

        $locations = Location::where('clinicID', $id)->get();

        $locationsservices=\App\Clinic::with('locations');

        var_dump($locationsservices);

        die();

        return view('clinic.show')->with(['locations' =>  $locations  ,'clinic'=>$clinic]);


    }


精慕HU
浏览 186回答 2
2回答

互换的青春

您可以使用关系获取此详细信息。在Clinic模型中,添加public function locations() {    return $this->belongsTo('App\Models\Locations','clinicID','clinicID'); }在Locations模型中,添加, public function location_services() {    return $this->hasOne('App\Models\LocationServices','locationID','locationID'); }在LocationServices模型上, public function services() {    return $this->hasOne('App\Models\Services','ServiceId','ServiceId'); }您可以通过以下方式获得结果,$clinic_info = Clinic::find($id);if(isset($clinic_info->locations)){  if(isset($clinic_info->locations->location_services))  {    if(isset($clinic_info->locations->location_services->services))    {      echo $clinic_info->locations->location_services->services->ServiceName;    }  }  }

一只萌萌小番薯

参考Maybe HelpFull为您服务多连接$data = DB::table('city')        ->join('state', 'state.state_id', '=', 'city.state_id')        ->join('country', 'country.country_id', '=', 'state.country_id')        ->select('country.country_name', 'state.state_name', 'city.city_name')        ->get();         return view('join_table', compact('data'));
打开App,查看更多内容
随时随地看视频慕课网APP