如何通过使用查询字符串值从数据库查询数据 [英] How to query data from database from using query string values
本文介绍了如何通过使用查询字符串值从数据库查询数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
作为一个初学者,我不知道该怎么做.我的控制器中有以下方法.
As a beginner I don't know how to go about this. I have the following method in my controller.
public function index(Request $request)
{
if (request(['condition','make','model','year'])) {
$vehicles = Vehicle::where('condition', $request->condition)
->where('make', $request->make)
->where('model', $request->model)
->where('year', $request->year)
->paginate(20);
} else {
$vehicles = Vehicle::paginate(20);
}
$conditions = DB::table("conditions")->pluck("name","id");
return view('cars',compact('conditions', 'vehicles'));
}
现在,我希望这样一种方式:如果我只有请求中的条件值(例如new),那么只有在搜索时才能看到新的车辆.到目前为止,只有在提供了所有键值的情况下,它才起作用!
Now I'd like it to be in a way that if I only have a condition value from the request e.g new then I can see new vehicles only on searching. As of now it only works when all the values of the keys are provided!
推荐答案
您需要检查$ request是否具有密钥
You need to check if the $request has the keys
尝试
public function index(Request $request)
{
$query = Vehicle::query();
if($request->has('condition')) {
$query->where('condition', $request->condition);
}
if($request->has('make')){
$query->where('make', $request->make);
}
if($request->has('model')) {
$query->where('model', $request->model);
}
if($request->has('year')){
$query->where('year', $request->year);
}
$vehicles = $query->paginate(20);
$conditions = DB::table("conditions")->pluck("name","id");
return view('cars',compact('conditions', 'vehicles'));
}
这篇关于如何通过使用查询字符串值从数据库查询数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文