Laravel 中某一个字段是逗号隔开时,查询其多选
想要前端传一个参数表示多选查询(platforms字段中既有facebook又有aiqiyi):示例前端传过来platforms:facebook,aiqiyi
实现方式:使用mysql自带的:FIND_IN_SET方法即可
代码如下:
public function index(Request $request) { $property_id = $request->property_id; $sortBy = $request->sortBy; $sortType = $request->sortType; $name = $request->name; $description = $request->description; $all = $request->all; $platforms = $request->platforms; $status = $request->status; $base_validation = $this->basic_validation($request,$property_id); if(!empty($base_validation)) { return $this->responseErrorWithMessage($base_validation); } $size = $request->size ?? 10; $video_list = Playlist::where('property_id', $property_id) ->when($sortBy && $sortType, function ($q) use ($sortBy, $sortType) { $q->orderBy($sortBy, $sortType); }) ->when($name,function($q) use($name){ $q->where('name','like','%'.$name.'%'); }) ->when($description,function($q) use($description){ $q->where('description','like','%'.$description.'%'); }) ->when($all,function($q) use($all){ return $q->where(function ($query) use ($all) { $query->orWhere('name', 'like', '%'.$all.'%') ->orWhere('description', 'like', '%'.$all.'%'); }); }) ->when($platforms,function($q) use($platforms){ return $q->where(function ($query) use ($platforms) { $platforms = explode(',',$platforms); if (count($platforms)) { foreach ($platforms as $platform) { $query->orWhereRaw('FIND_IN_SET(?,platforms)',$platform); } } }); }) ->when(!is_null($status),function($q) use($status){ $q->whereIn('status',explode(',', $status)); }) ->paginate($size); return $this->responseSuccessWithExtrasAndMessage(PlaylistResource::collection($video_list)->resource); }