gpt4 book ai didi

laravel-4 - 删除相关的 hasManyThrough 模型

转载 作者:行者123 更新时间:2023-12-03 08:26:12 24 4
gpt4 key购买 nike

我有一些像这样彼此相关的模型:

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())确实包含连接...

有人知道这里出了什么问题吗?

最佳答案

Query Builder delete method() 的工作方式与其他方法略有不同,因此它会改变查询并且没有连接 - 它只是采用“wheres”并省略构建器的其他部分。据说要实现你想要的使用其中之一:

// 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!

关于laravel-4 - 删除相关的 hasManyThrough 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23272159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com