删除相关的hasManyThrough模型

时间:2014-04-24 14:40:58

标签: laravel-4 eloquent relational-database

我有一些与彼此相关的模型:

Order
  - hasMany(CartItem)
  - hasManyThrough(Product, CartItem)

CartItem
  - belongsTo(Order)
  - hasOne(Product)

Product
  - belongsTo(CartItem)

通过调用动态属性和方法表单(例如$order->products$order->products()订购模型),验证所有关系都在工作。

现在我想删除与特定订单相关的所有产品,所以我尝试了这个(订单ID = 3):

Order::find(3)->products()->delete()

然而,这不起作用。出于某种原因,我收到错误消息,指出无法找到加入列:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cart_items.order_id' in 'where clause' (SQL: delete from `products` where `cart_items`.`order_id` = 3)  

原始SQL输出(使用toSql())确实包含了连接...

任何人都知道这里有什么问题吗?

1 个答案:

答案 0 :(得分:6)

查询生成器删除方法()与其他方法有点不同,因此它会改变查询并且没有连接 - 它只是需要' whebe'并且省略了建造者的其他部分。 据说可以实现你想要的东西之一:

// This will run delete query for every product
Order::find(3)->products->each(function ($product) {
   $product->delete();
});


// This will run only single query for all of them, which is obviously faster
$productsIds = Order::find(3)->products->modelKeys();
Product::whereIn('id', $productsIds)->delete();

请注意,这两种方法都会从数据库中删除行,但不会从集合中移除模型:

$order = Order::find(3);
// run deletes
$order->products; // Collection still contains all the models!
相关问题