使用可选查询参数使用雄辩的数据库检索记录 [英] Retrieving records from database using eloquent with optional query parameters
问题描述
$ travel_company_id =输入::得到( 'travel_company_id');
$ transport_type = Input :: get('transport_type');
$ route_type = Input :: get('route_type');
$ travelRoutes = TravelRoute :: where('travel_company_id',$ travel_company_id)
- > where('transport_type',$ transport_type)
- > where('route_type ',$ route_type)
- > get();
现在,这是根据提供的参数获取 travelRoutes 。我想要做的是根据可用参数执行搜索,如果 $ route_type 为空,则搜索将仅对travel_company_id和传输类型执行
另外,如果所有参数都是空,那么它只会做一个get并返回所有可用的记录。
我知道我可以用很多if语句来做到这一点,但是如果我在前端添加一个新参数,我将不得不将其添加到后端,我想知道是否有更简单的和更短的方式在laravel中执行此操作。
其中
方法接受一个约束数组:
$ constraints = array_only(Input :: all(),[
'travel_company_id',
'transport_type',
'route_type',
]);
$ routes = TravelRoute :: where($ constraints) - > get();
警告:do 不使用 Input :: only()
而不是 array_only()
。它们不一样。
Input :: only()
使用<$ c填写任何缺少的项目$ c> null ,这不是你想要的。
i have the following block of code in my Resource Controller:
$travel_company_id = Input::get('travel_company_id');
$transport_type = Input::get('transport_type');
$route_type = Input::get('route_type');
$travelRoutes = TravelRoute::where('travel_company_id', $travel_company_id)
->where('transport_type', $transport_type)
->where('route_type', $route_type)
->get();
Now what this does is it gets travelRoutes based on the parameters supplied. What i want is for it to do is perform a search based on the available parameters, that way if $route_type is empty the search will be performed only on travel_company_id and transport type.
Also if all the parameters are empty then it will simply do a get and return all available records.
I know i can do this with lots of if statements but then if i add a new parameter on the frontend i will have to add it to the backend as well, I was wondering if there was a much simpler and shorter way to do this in laravel.
The where
method accepts an array of constraints:
$constraints = array_only(Input::all(), [
'travel_company_id',
'transport_type',
'route_type',
]);
$routes = TravelRoute::where($constraints)->get();
Warning: do not use Input::only()
instead of array_only()
. They're not the same.
Input::only()
fills in any missing items with null
, which is not what you want here.
这篇关于使用可选查询参数使用雄辩的数据库检索记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!