【问题标题】:Laravel 5: Alternative for Eloquent's 'orWhere' method for querying collectionsLaravel 5:替代 Eloquent 的 'orWhere' 查询集合的方法
【发布时间】: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


【解决方案1】:

类似于 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);
})

它确保将过滤后的集合分配给一个变量。它还使用strstr 作为stripos 的替代品,尽管我怀疑这是问题的原因。

【讨论】:

  • 它适用于collect($this->products)->filter()$this->products->filter(),但没有使用stripos,仅适用于strstr,似乎strstr 区分大小写,而stripos 不区分大小写.
  • 它与stristr 一起工作,这是strstr 的替代方案,但不区分大小写,就像stripos 一样。我会将您的答案标记为已接受,因为它引导我使用stristr
【解决方案2】:

尝试使用 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));
});

这里 $search 是您要搜索的值。

【讨论】:

  • 由于某种原因,无论搜索词是否与字段值匹配,该代码的结果都是一个空集合。虽然代码对我来说看起来是正确的......
  • 您的代码大部分是正确的,但 Sholt 基于您的回答解决了我的问题。还是谢谢你!
猜你喜欢
  • 2015-02-22
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 2021-08-17
  • 2018-01-30
  • 2021-11-06
  • 2015-06-06
  • 1970-01-01
相关资源
最近更新 更多