Retrieving records from database using eloquent with optional query parameters

一世执手 提交于 2019-12-24 16:15:25

问题


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.


回答1:


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.




回答2:


This is pretty hacky and if you spend some time developing a solution I'm sure it could be much nicer. This assumes all the fields in the getSearchFields() function match the input names from the form and database.

/**
 * Search fields to retrieve and search the database with. Assumed they match the 
 * column names in the database
 */
private function getSearchFields()
{
    return ['travel_company_id', 'transport_type', 'route_type'];
}

public function search()
{
    // Get a new query instance from the model
    $query = TravelRoute::query();

    // Loop through the fields checking if they've been input, if they have add 
    //  them to the query.
    foreach($this->getSearchFields() as $field)
    {
        if (Input::has($field))
        {
            $query->where($field, Input::get($field));
        }
    }

    // Finally execute the query
    $travelRoutes = $query->get();
}


来源:https://stackoverflow.com/questions/31705032/retrieving-records-from-database-using-eloquent-with-optional-query-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!