Laravel 使用嵌套集合删除嵌套分支

Laravel working with nested collection delete nested branch

无法删除 "product" => null 中的所有嵌套分支 有疑问

$cartWhere['user_id'] = $user_id;
$cartWhere['site_id'] =$currentSite->id;

$item = Cart::select('product_id','quantity')->with(['product' => function($product) use ($search){
$product->join('product_translations', 'products.id', '=', 'product_translations.product_id');
$product->where( 'product_translations.name', 'LIKE','%'.$search.'%');
        },'product.manufacturer:id,name'])
->where($cartWhere)->get();

然后我收到包含所有已过滤购物车的集合,但其中一些购物车与产品有关系 => null

  1 => App\Models\Cart {#736 ▼
      ...
      #original: array:2 [▼
        "product_id" => 1
        "quantity" => 2
      ]
     ...
      #relations: array:1 [▼
        "product" => App\Models\Product {#785 ▶}
      ]
  }
  2 => App\Models\Cart {#736 ▼
      ...
      #original: array:2 [▼
        "product_id" => 2
        "quantity" => 2
      ]
     ...
      #relations: array:1 [▼
        "product" => null
      ]
  }

对不起我的英语

您可以使用集合 filter() 方法

从结果中过滤它们
$item = Cart::select('product_id','quantity')
            ->with(['product' => function($product) use ($search) {
                $product->join('product_translations', 'products.id', '=', 'product_translations.product_id');
                $product->where( 'product_translations.name', 'LIKE','%'.$search.'%');
            }, 'product.manufacturer:id,name'])
           ->where($cartWhere)
           ->get()
           ->filter(function ($cart) {
               return $cart->product !== null;
           });

除了 with,您还应该使用 whereHas。因此结果将不包括与 null 值的任何关系。所以这样你也可以避免使用额外的filter方法。