【发布时间】:2017-02-14 15:30:44
【问题描述】:
所以我有一个产品集合 ($this->products),我是通过模型查询获得的,我想通过它的一些属性值对其进行过滤。问题是 Laravel 没有像 orWhere 这样的方法来像 Eloquent 那样用于查询模型的集合。我还想使用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}%");
我想直接查询模型,但我只是将$products 集合存储在 Session 中,这样我就可以在需要的任何地方使用它,我不想经常查询数据库,所以我正在寻找一个以某种方式过滤现有集合的解决方案。
【问题讨论】:
-
是的,您需要自己编写这种类型的逻辑。使用collection 方法(您可能需要
->filter),但它们不提供完整的类似SQL 的查询。 -
你试过
$this->products()->where(...)->orWhere(...)->get();吗?$this->products正在尝试访问属性,但$this->products()将尝试访问public function products(){ ... }方法。
标签: php laravel laravel-5 laravel-5.1