在 Laravel 4 中搜索和过滤/优化数据库结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19830561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:38:08  来源:igfitidea点击:

Searching and filtering / refining database results in Laravel 4

phpmysqllaravellaravel-4

提问by nathan

I'm looking for a way to search and filter a database table / Eloquent model through the query string in Laravel 4.

我正在寻找一种通过 Laravel 4 中的查询字符串搜索和过滤数据库表/Eloquent 模型的方法。

I have a table named houseswith the columns named: price, name, hasCoffeeMachineand hasStove

我有一个以houses列命名的表:price, name,hasCoffeeMachinehasStove

I want the user to be able to do something like: http://example.com?name=test&hasCoffeeMachine=1

我希望用户能够执行以下操作:http: //example.com?name=test&hasCoffeeMachine=1

Which will get all the rows where the name is "test" and they have a coffee machine.

这将获得名称为“test”的所有行,并且他们有一台咖啡机。

I want the user to be able to add URL parameters based on the filter they desire. What is the best way to account for all the possible combinations of query strings to return the correct results from the table?

我希望用户能够根据他们想要的过滤器添加 URL 参数。考虑查询字符串的所有可能组合以从表中返回正确结果的最佳方法是什么?

回答by user1669496

$houses = new House;

if(Input::get('name'))
    $houses->where('name', '=', Input::get('name'));

if(Input::get('hasCoffeeMachine'))
    $houses->where('hasCoffeeMachine', '=', Input::get('hasCoffeeMachine'));

// Keep adding more for every filter you have

// Don't do this till you are done adding filters.
$houses = $houses->get();

回答by Pnar Sbi Wer

alternatively you could build and pass in an array into the where clause https://laravel.com/docs/5.2/queries#where-clauses

或者,您可以构建数组并将其传递到 where 子句中https://laravel.com/docs/5.2/queries#where-clauses

$houses = $houses->where([
    ['hasCoffeeMachine',1],
    ['price','<','1000'],
])->get();

You can build your array with any conditional statements.

您可以使用任何条件语句构建数组。