php - 删除/分离第一个数据透视表记录

标签 php mysql laravel pivot-table laravel-5.3

案例
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

问题

假设我想删除到第 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/

相关文章:

mysql - 使用前缀和组总和连接多个 mysql 表

php - base64编码图像而不保存

php - 将集合检索方法添加到模型中

php - 有没有更有效的方法来编写这 4 个 MYSQL 查询以使用更少的查询?

mysql - 如何替换 MySQL 枚举值进行排序

php - PHP 和 MySQL 上的 Friendsystem

Laravel Sanctum CSRF Coo​​kie 请求可选

php - Laravel - 多个表的单个模型

laravel - Axios 删除不起作用

php - 在 php 中使用 openssl 进行 AES-256-CBC 加密/解密十六进制字符串