gpt4 book ai didi

php - 拉维尔 5 : Alternative for Eloquent's 'orWhere' method for querying collections

转载 作者:可可西里 更新时间:2023-11-01 00:08:17 25 4
gpt4 key购买 nike

所以我有一个产品集合 ($this->products),这是我通过模型查询得到的,我想通过它的一些属性值来过滤它。问题是 Laravel 没有类似 orWhere 的方法用于集合,就像 Eloquent 用于查询模型一样。此外,我想使用 LIKE %{$searching_for}% 通配符,但我不确定如何使用它(如果可能的话)来过滤我的收藏。

这是我试图过滤我的集合的代码,显然会抛出 orWhere 方法不存在的 Exception:

$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 中,这样我就可以在任何需要的地方使用它,我不想太频繁地查询数据库我正在寻找以某种方式过滤现有集合的解决方案。

最佳答案

类似于 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 的替代品,尽管我怀疑这是问题的原因。

关于php - 拉维尔 5 : Alternative for Eloquent's 'orWhere' method for querying collections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42230081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com