I have the following tables
- People
- Locations
- People_Locations
The people table has a person_type_id column, this denotes whether they are a guest or an employee.
I'd like to query the people table to return all guests and only return employees when at a given location.
Example people data:
id | full_name | person_type_id
-----------------------------------------
1 | Paul Sample | 1
2 | Kieth Sample | 1
3 | Mary Sample | 2
4 | Julie Sample | 2
5 | Mark Sample | 1
Example Location data:
id | name
-------------------
1 | Location A
2 | Location B
3 | Location C
Example people_location data:
id | person_id | location_id
--------------------------------------
1 | 3 | 1
2 | 3 | 2
3 | 4 | 1
4 | 4 | 2
5 | 4 | 3
Query Parameters
- full_name LIKE 'Sample'
- location_id = 1
This query should return all people regardless of location when their person_type_id = 2 but when the person_type_id = 1 the location parameter should be applied
I've tried to use eloquent but I'm struggling when I get to the if statement on the person_type_id because the query hasn't run so I'm unsure how you would query.
Attempt
My attempt below returns all people at the given location which is due to the whereHas but I'm unsure how you would specify only run the whereHas location when the person_type_id = 1.
$data = (new \App\People)->newQuery();
if($request->searchterm){
$data->where('full_name','LIKE','%' . $request->searchterm . '%');
};
if($request->location){
$data->whereHas('locations',function($q) use($request) {
$q->where('location_id',$request->location);
});
};
$people = $data->get();
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire