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
JavaScript
x
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
JavaScript
public function locations()
{
return $this->belongsTo('AppModelsLocations','clinicID','clinicID');
}
In the Locations
model,add,
JavaScript
public function location_services()
{
return $this->hasOne('AppModelsLocationServices','locationID','locationID');
}
On the LocationServices
model,
JavaScript
public function services()
{
return $this->hasOne('AppModelsServices','ServiceId','ServiceId');
}
You can get the result by,
JavaScript
$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;
}
}
}