在$categroy_id - $country_id - $city_id
的搜索中。有一个表activities
具有所有价值。
我只是在我的控制器中实现一个函数,但它返回所有数据。
我的控制器功能代码:
public function PlanActivity(Request $request){
$category_id = $request->category_id;
$countryid = $request->country_id;
$cityid = $request->city_id;
$listactivity = Activity::all(); // get all activity
if($category_id != '') {
$listactivity->where('category_id', function ($query) use ($category_id) {
$query->where('category_id', $category_id);
});
}
return view('front.plan_activity',compact('listactivity'));
}
我该怎么做?
答案 0 :(得分:4)
使用多个where子句:
查询构建器
// match any one of the values
$activities = DB::table('activities')->where('category_id', $category_id)
->orWhere('country_id', $country_id)
->orWhere('city_id', $city_id)
->get();
// match all of the values
$activities = DB::table('activities')->where('category_id', $category_id)
->where('country_id', $country_id)
->where('city_id', $city_id)
->get();
锋
// match any one of the values
$activities = Activity::where('category_id', $category_id)
->orWhere('country_id', $country_id)
->orWhere('city_id', $city_id)
->get();
// match all of the values
$activities = Activity::where('category_id', $category_id)
->where('country_id', $country_id)
->where('city_id', $city_id)
->get();
// this can be merged together in one array
$activities = Activity::where([
'category_id' => $category_id,
'country_id' => $country_id,
'city_id' => $city_id
])->get();
如果请求参数为空
public function PlanActivity(Request $request){
if (!$categroy_id && !$country_id && !$city_id) {
$activities = Activity::all();
} else {
// do the above queries
}
return view('front.plan_activity',compact('activities'));
}
答案 1 :(得分:0)
你的错误在于使用Laravel模型提供的雄辩功能。当您调用all()
函数时,它基本上会对您的表执行SELECT * FROM
并将结果作为对象返回。如果您需要过滤此查询或添加任何内容,则不再使用all()
,而是使用get()
作为最后一项功能。
至于在模型上设置此查询,您已经在模型中!当您调用Activity::whatever-function-next()
时,您就在模型中,并且Laravel已经为您提供了所有这些功能,可以轻松地创建查询。第一个答案为您提供了所需的一切,请务必了解这些函数和类实际上在做什么。
答案 2 :(得分:0)
您可以使用此查询执行搜索
public function PlanActivity(Request $request)
{
$category_id = $request->category_id;
$country_id = $request->country_id;
$city_id = $request->city_id;
$activity = new Activity; // get all activity
$search = $activity->search();
if($category_id) {
$search->where('category_id', $category_id);
}
if($country_id){
$search->where('country_id', $country_id);
}
if($city_id){
$search->where('city_id', $city_id);
}
$listactivity = $search->
return view('front.plan_activity',compact('listactivity'));
}
答案 3 :(得分:0)
首先,您需要为活动表创建一个模型。
class Activity extends Model
{
protected $table = 'activities'; //table name
protected $guarded = [];
}
然后你可以像上面所说的那样编写查询
$activities = Activity::where('category_id', $category_id)
->orWhere('country_id', $country_id)
->orWhere('city_id', $city_id)
->get();