繁体   English   中英

如何在 Laravel 集合中使用多个 whereIn

[英]How to use multiple whereIn in Laravel collection

我有一个 arrays 的集合,我试图根据我传入的$prices值返回。 $prices = ['100', '200'];

 $collection = collect([
   ['product' => 'Desk', 'price' => 100, 'price2' => 150],
   ['product' => 'Chair', 'price' => 150, 'price2' => 200],
   ['product' => 'Bookcase', 'price' => 300, 'price2' => 350],
   ['product' => 'Door', 'price' => 400, 'price2' => 200],
   ['product' => 'Door', 'price' => 450, 'price2' => 500],
 ]);

 $filtered = $collection->whereIn('price', $prices)->whereIn('price2', $prices);

 $filtered->all();

/* The result should return where price or price2 is 100 or 200:
  [
    ['product' => 'Desk', 'price' => 100, 'price2' => 150],
    ['product' => 'Chair', 'price' => 150, 'price2' => 200],
    ['product' => 'Door', 'price' => 400, 'price2' => 200],
  ]
*/

您可以使用集合filter而不是 whereIn:

$prices = ['100', '200'];
$collection = collect([
    ['product' => 'Desk', 'price' => 100, 'price2' => 150],
    ['product' => 'Chair', 'price' => 150, 'price2' => 200],
    ['product' => 'Bookcase', 'price' => 300, 'price2' => 350],
    ['product' => 'Door', 'price' => 400, 'price2' => 200],
    ['product' => 'Door', 'price' => 450, 'price2' => 500],
]);
    
$filtered = $collection->filter(function ($value, $key) use ($prices) {
    return (in_array($value['price'], $prices) || in_array($value['price2'], $prices)) ? true : false ;
});
$filtered->all();

您可以使用 wherebetween 来获取价格范围内的数据。

$filtered = $collection->whereBetween('price', [100, 200]);

$filtered->all();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM