【问题标题】:Delete/detach first pivot table records删除/分离第一个数据透视表记录
【发布时间】:2017-01-05 19:33:57
【问题描述】:

案例
Laravel 5.3

CartProduct 之间有一个带有附加列的数据透视表:

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_idproduct_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


【解决方案1】:

如果您只想删除此表中的一行,则不能使用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();

【讨论】:

  • 这会导致调用未定义的方法 stdClass::delete()
  • 您确定您没有使用first()find() 或其他东西吗?因为syntax is correct
  • 好的,您已经更新了您的问题,并且您已将first() 添加到我的代码中。删除它,只需使用我的答案中的代码而不进行修改。
  • 那你为什么要发布这个代码$product->carts()->detach($itemId);?我已经用你需要的代码更新了我的代码。
  • 因为我在 cart_product 表上查询后运行了该函数,但你的最新答案就像一个魅力!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
相关资源
最近更新 更多