Ese*_*eth 3 php laravel laravel-5 laravel-5.1
所以我有一个产品集合($this->products)我得到的模型查询的结果,我想通过它的一些属性值过滤它.问题是Laravel没有像Eloquent那样orWhere的集合方法来查询模型.另外我想使用LIKE %{$searching_for}%通配符,我不知道如何使用它(如果可能的话)来过滤我的集合.
这是我试图过滤我的集合的代码,显然抛出了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}%");
Run Code Online (Sandbox Code Playgroud)
我想直接查询模型,但我只是将$products集合存储在Session中,这样我就可以在任何需要的地方使用它,我不想经常查询数据库所以我正在寻找一种解决方案以某种方式过滤现有的采集.
类似于 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);
})
Run Code Online (Sandbox Code Playgroud)
它确保将过滤后的集合分配给一个变量。它也strstr用作替代方案,stripos尽管我怀疑这是问题的原因。
尝试使用laravel collection的过滤方法.
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));
});
Run Code Online (Sandbox Code Playgroud)
这里$ search是您要搜索的值.