Laravel 9中如何用Arr::where()按商品shop_id过滤购物车数组
使用Laravel Arr::where()过滤cart_items数组(基于关联product的shop_id)
假设你的cart_items数组结构如下(每个元素包含关联的product数据):
$cartItems = [ [ 'id' => 1, 'product' => ['id' => 101, 'shop_id' => 5, 'name' => '商品A'], // 其他购物车字段 ], [ 'id' => 2, 'product' => ['id' => 102, 'shop_id' => 6, 'name' => '商品B'], // 其他购物车字段 ], ];
正确过滤实现
引入Arr类后,通过闭包判断每个购物车项的关联product的shop_id是否匹配目标值:
use Illuminate\Support\Arr; $targetShopId = 5; // 你要匹配的店铺ID $filteredCartItems = Arr::where($cartItems, function ($item) use ($targetShopId) { // 先确保product及shop_id存在,避免报错 return isset($item['product']['shop_id']) && $item['product']['shop_id'] === $targetShopId; });
如果product是Eloquent模型实例
如果你的cart_items元素是Eloquent模型,且product是关联模型,调整判断逻辑:
$filteredCartItems = Arr::where($cartItems, function ($item) use ($targetShopId) { return $item->product && $item->product->shop_id === $targetShopId; });
常见问题说明
之前用if判断未成功,大概率是以下原因:
- 未处理
product为空的情况,导致调用shop_id时报错 - 使用了松散相等
==而非严格相等===,引发类型不匹配问题 - 遍历逻辑有误,未正确遍历每个购物车项并筛选
内容的提问来源于stack exchange,提问作者Joe collins
相关产品推荐
相关产品推荐

