案例
Laravel 5.3
在CCD_ 1&带有附加列的Product
:
id - cart_id - product_id - item_id (additional column)
1 - 1 - 1 - 5
2 - 1 - 1 - 6
3 - 1 - 1 - 7
4 - 2 - 1 - 8
通常使用以下方法分离数据透视表记录:$product->carts()->detach($cartId);
但在这种情况下,存在具有相同cart
&product
id
问题
比方说我想删除row 1
。
我希望工作的是以下其中之一:$product->carts()->detach($itemId);
或$product->carts()->detach($cartId)->first();
如果我基于CCD_ 10&Cart
1,调用first
&对该查询结果运行delete()
,Call to undefined method stdClass::delete()
将返回
$firstItem = DB::table('cart_product')
->where('cart_id', $cart_id)
->where('product_id', $product->id)
->first();
$firstItem->delete();
尽管当我查询数据后dd()
$firstItem
时,它会返回一个(正确的)对象
{#238 ▼
+"id": 1
+"cart_id": 1
+"product_id": 1
+"item_id": 5
}
如果只想删除该表中的一行,则不能使用detach()
。
如果你只想删除第一个项目,只需使用这个:
DB::table('cart_product')
->where('cart_id', $cart_id)
->where('product_id', $product->id)
->take(1)
->delete();
或者从您的代码:
$id = DB::table('cart_product')
->where('cart_id', $cart_id)
->where('product_id', $product->id)
->first()->id;
DB::table('cart_product')
->where('id', $id)
->delete();