案例
Laravel 5.3
在 Cart
和 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
问题
假设我想删除到第 1 行
。
我希望工作的是以下其中之一:
$product->carts()->detach($itemId);
或者
$product->carts()->detach($cartId)->first();
如果我根据cart_id
& product_id
查询数据透视表,调用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();
关于php - 删除/分离第一个数据透视表记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41493231/