从数据透视表中删除特定记录



我有产品存储在products表中。我还在order_product表中存储了订单产品。

假设我有一个id为53的产品,我将其丢弃。然后在order_product表中,我需要获得与我已经销毁的产品相关的特定记录。在我得到记录后,我应该删除它。但如果产品被扔进垃圾桶,这是行不通的。出了什么问题,需要做什么?

$product = Product::withTrashed()->findOrFail($id);
$orderProduct = DB::table('order_product')->where('product_id', $product->id); // it's not working if the product is in trash. 
if ($orderProduct) {
$orderProduct->delete(); 
}

(结案)我找到问题了。它不工作,因为上面的代码位于foreach内部。不知怎么的,它不工作。但是当我把它移到foreach之外,它就工作了。

最佳删除选项通过迁移添加外键

Schema::table('order_product', function (Blueprint $table) {
$table->unsignedBiginteger('product_id')->nullable();
...
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});

不需要编写额外的代码来删除

最新更新