Skip to content
Advertisement

Laravel Join query is not working for 4 tables

I have 4 tables

Table Name : Clinics

Fields: clinicID , clinicName

Table Name : locations

Fileds: locationID, clinicID,locationname

Table Name : Services

Fields: ServiceId , ServiceName

Table Name: LocationServices

Fields: locationServiceID, locationID , ServiceId

My requiremnt is that when i pass clinicID, i need to retrive Corresponding clinics service name, there may be more than one.

But when i tried join query is not working Following is my code in controller

 public function showClinic($id)
    {
        $clinic = Clinic::find($id);
        $locations = Location::where('clinicID', $id)->get();
        $locationsservices=AppClinic::with('locations');
        var_dump($locationsservices);
        die();
        return view('clinic.show')->with(['locations' =>  $locations  ,'clinic'=>$clinic]);

    }

Advertisement

Answer

You can get this details by using relationships. In the Clinic model,add

public function locations()
 {
    return $this->belongsTo('AppModelsLocations','clinicID','clinicID');
 }

In the Locations model,add,

 public function location_services()
 {
    return $this->hasOne('AppModelsLocationServices','locationID','locationID');
 }

On the LocationServices model,

 public function services()
 {
    return $this->hasOne('AppModelsServices','ServiceId','ServiceId');
 }

You can get the result by,

$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;
    }
  }  
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement