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

时间:2017-01-05 19:33:58

标签: php mysql laravel pivot-table laravel-5.3

案例
   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&amp ;;查询数据透视表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
}

1 个答案:

答案 0 :(得分: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();
相关问题