i have User model that have many to many relation with Area model and the Area Model have one to many relation with City Model and i want to filter users by city
public function search(Request $request){
return User::where('status', 1)->where('type', User::TYPE_INSTRUCTOR)
->where(function ($query) use ($request) {
if($request->city){
$areas = Area::where('city_id',$request->city)->get();
foreach($areas as $area){
$query->area($area);
}
}
if ($request->area) {
$query->area($request->area);
}
})
->orderBy('id')->paginate(8);
}
and i make this function in User model
public function scopeArea($query, $search){
$query->whereHas('areas', function (Builder $query) use ($search){
$query->where('area_id', $search);
});
}
CodePudding user response:
You can use the following code for filtering
$query = DB::table('users')
->leftjoin('areas','users.id', '=' , 'areas.user_id')
->leftjoin('cities','areas.id', '=' , 'cities.areas_id');
if(!empty($cityId)){
$query->where('cities.id','=' , $cityId);
}
$result = $query->get();
CodePudding user response:
i solved the problem by add this cas
if($request->city){
$areas = Area::where('city_id',$request->city)->pluck('id')->toArray();
$query->whereHas('areas', function (Builder $query) use ($areas){
$query->whereIn('area_id', $areas);
});
}