Laravel 5:Eloquent 用于查询集合的“orWhere”方法的替代方案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42230081/
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 5: Alternative for Eloquent's 'orWhere' method for querying collections
提问by Eseth
So I have a collection of products ($this->products
) which I'm getting as a result of a Model query and I want to filter it by some of its attributes values. The problem is that Laravel doesn't have a method like orWhere
for collections like Eloquent does for querying models. Also I want to use the LIKE %{$searching_for}%
wildcard and I'm not sure how to use it (if possible at all) to filter my collection.
所以我有一个产品集合 ( $this->products
) 作为模型查询的结果,我想通过它的一些属性值来过滤它。问题是 Laravel 没有像 EloquentorWhere
那样用于查询模型的集合方法。我也想使用LIKE %{$searching_for}%
通配符,但我不确定如何使用它(如果可能的话)来过滤我的收藏。
This is the code I tried to filter my collection with which obviously throws an Exception
that orWhere
method doesn't exist:
这是我试图筛选我收藏有这显然抛出的代码Exception
是orWhere
方法不存在:
$products = $this->products
->where("field1", "LIKE %{$searching_for}%")
->orWhere("field2", "LIKE", "%{$searching_for}%")
->orWhere("field3", "LIKE", "%{$searching_for}%")
->orWhere("field4", "LIKE", "%{$searching_for}%");
I'd like to query the Model directly but I just store the $products
collection in Session so I can use it anywhere I need, I don't want to query the database too often so I'm searching for a solution to somehow filter the existing collection.
我想直接查询模型,但我只是将$products
集合存储在 Session 中,这样我就可以在任何需要的地方使用它,我不想太频繁地查询数据库,所以我正在寻找一种解决方案以某种方式过滤现有的收藏。
采纳答案by Spholt
Similar to how Saravanan suggests doing it try this:
类似于 Saravanan 建议这样做的方式,试试这个:
$products = $this->products->filter(function($product) use ($searching_for) {
return strstr($product->field1, $searching_for) ||
strstr($product->field2, $searching_for) ||
strstr($product->field3, $searching_for) ||
strstr($product->field4, $searching_for);
})
It is making sure to assign the filtered collection to a variable. It is also using strstr
as an alternative to stripos
though i doubt that is the cause of the issue.
它确保将过滤后的集合分配给一个变量。它也strstr
用作替代方案,stripos
尽管我怀疑这是问题的原因。
回答by Saravanan Sampathkumar
Try using laravel collection's filter method.
尝试使用 Laravel 集合的过滤方法。
collect($this->products)->filter(function($value) use ($search) {
return (stripos($value->field1, $search) ||
stripos($value->field2, $search) ||
stripos($value->field3, $search) ||
stripos($value->field4, $search));
});
Here $search is the value that you wanted to search.
这里 $search 是您要搜索的值。