【发布时间】:2017-01-05 19:33:57
【问题描述】:
案例
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
问题
假设我想删除到row 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
}
【问题讨论】:
-
根据我的理解和经验,
$product->carts()->detach($itemId);应该可以工作。你得到什么样的错误? -
@devk 仔细看看。
$itemId是附加列的 ID,但不是cart_id。 -
@AlexeyMezenin 哦,我明白了。
$product->carts()->where('cart_product.item_id', $itemId)->detach()不应该工作吗?假设关系中有->withPivot(['item_id'])。 -
@devk 我不确定,请 Liam 试试。 ) 而且他的代码还不知道项目 ID,他需要先得到它。
标签: php mysql laravel pivot-table laravel-5.3