在Laravel中过滤查询结果

在Laravel中过滤查询结果,laravel,eloquent,where-clause,Laravel,Eloquent,Where Clause,我尝试使用以下命令查询数据库: $products = Product::where('available', true)->get(); 然后我想将$products传递给另一个函数,以便对其执行更多过滤 $finalResult = $ProductInstance->searchProducts($products); 知道searchProducts的功能编写如下: public function searchProducts($products, $searchValu

我尝试使用以下命令查询数据库:

$products = Product::where('available', true)->get();
然后我想将$products传递给另一个函数,以便对其执行更多过滤

$finalResult = $ProductInstance->searchProducts($products);
知道searchProducts的功能编写如下:

public function searchProducts($products, $searchValue){
 $finalProducts= $products->where('name', 'LIKE', "%{$searchValue}%")->get();
}
这不起作用,因为从第一行代码返回的结果存储在集合中。我该怎么做

谢谢

searchProducts($products,$searchValue){
…这里的$products是一个集合实例,而不是查询生成器

您必须与stripos()一起使用,以模拟
'%.$searchValue'%'

public function searchProducts($products, $searchValue){
    return $products->filter(function ($product) use ($searchValue) {
        return false !== stripos($product['name'], $searchValue);
    });
}
请在下面的评论中向我发布。

searchProducts($products,$searchValue){
…这里的$products是一个集合实例,而不是查询生成器

您必须与stripos()一起使用,以模拟
'%.$searchValue'%'

public function searchProducts($products, $searchValue){
    return $products->filter(function ($product) use ($searchValue) {
        return false !== stripos($product['name'], $searchValue);
    });
}

请在下面的评论中留言。

$products=Product::where('available',true)->get();
返回一个,它不支持
->where('name','LIKE',“%{$searchValue}%”中的
LIKE
where功能

改变

$products = Product::where('available', true)->get();


这将返回一个对象,您可以向其添加额外的数据库查询,并最终从
searchProducts()
方法返回一个集合。

$products=Product::where('available',true)->get();
返回一个,它不支持
->where('name',LIKE',“%中的
LIKE
where功能{$searchValue}%”

改变

$products = Product::where('available', true)->get();


这将返回一个对象,您可以向其中添加额外的数据库查询,并最终从
searchProducts()
方法返回一个集合。

不要在第一行代码中使用
->get()
,因为
->get()
返回一个集合。不使用它会返回一个QueryBuilder,您可以通过它传递额外的QueryBuilder子句onYeah true。谢谢。如果您将其作为帖子编写,我可以将其设置为正确答案。不要在第一行代码中使用
->get()
,因为
->get()
返回一个集合。不使用它会返回一个QueryBuilder,您可以通过它传递额外的QueryBuilder子句onYeah true。谢谢。如果您将其作为帖子编写,我可以将其设置为正确答案。事实上,正如一条评论中指出的那样,我只需删除第一个查询中的get。但我有兴趣了解您编写的代码注意:你能解释一下这个位返回false吗!==stripos($product['name',$searchValue);实际上正如一个评论中指出的那样,我只需要从第一个查询中删除get。但是我对理解你编写的代码感兴趣。你能解释一下这个位返回false吗!==stripos($product['name',$searchValue));