MySQL Laravel 多列雄辩搜索查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25599540/
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
Laravel multiple column eloquent search query
提问by Md. Tanvir Raihan
i am very new in Laravel,currently working with Laravel4.I am trying to add a multiple column search functionality in my project.I can do single column eloquent search query,But honestly i have no idea how to do multiple column eloquent search query in laravel.I have two drop down menu
我是 Laravel 的新手,目前正在使用 Laravel4。我正在尝试在我的项目中添加多列搜索功能。我可以进行单列雄辩搜索查询,但老实说,我不知道如何进行多列雄辩搜索查询laravel.我有两个下拉菜单
1.Locatiom 2.blood group.
1.位置 2.血型。
i want to search an userhaving certain blood groupagainst certain location.That is, user will select a locationand blood groupfrom those two drop down menu at a time and hit the search button.
我想针对特定位置搜索具有特定血型的用户。也就是说,用户将从这两个下拉菜单中一次选择一个位置和血型,然后点击搜索按钮。
In my database,i have two column, one contains the locationand another contains the blood groupof a certain user. Now,what should be the eloquent query for such a search?
在我的数据库中,我有两列,一列包含位置,另一列包含某个用户的血型。现在,这种搜索的雄辩查询应该是什么?
回答by Jarek Tkaczyk
Simply chain where
for each field you need to search through:
只需链接where
您需要搜索的每个字段:
// AND
$results = SomeModel::where('location', $location)->where('blood_group', $bloodGroup)->get();
// OR
$results = SomeModel::where('location', $location)->orWhere('blood_group', $bloodGroup)->get();
You can make it easier to work with thanks to the scopes:
借助范围,您可以更轻松地使用:
// SomeModel class
public function scopeSearchLocation($query, $location)
{
if ($location) $query->where('location', $location);
}
public function scopeSearchBloodGroup($query, $bloodGroup)
{
if ($bloodGroup) $query->where('blood_group', $bloodGroup);
}
// then
SomeModel::searchBloodGroup($bloodGroup)->searchLocation($location)->get();
Just a sensible example, adjust it to your needs.
只是一个明智的例子,根据您的需要进行调整。
回答by Zir Abiodun G. Quadri
This is a great way but I think there is an error somewhere as laravel would not allow you to access a non-static function so instead of using
这是一个很好的方法,但我认为某处存在错误,因为 Laravel 不允许您访问非静态函数,因此不要使用
SomeModel::searchBloodGroup($bloodGroup)->searchLocation($location)->get();
you could simply use
你可以简单地使用
SomeModel::BloodGroup($bloodGroup)->Location($location)->get();
take note of the searchBloodGrouphas been changed to BloodGroup, that's how you will use it for all others also.
请注意searchBloodGroup已更改为BloodGroup,这也是您将其用于所有其他人的方式。