2017-01-05 12 views
2

ケース
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 & productid

である問題

私はrow 1に削除したいとしましょう。私は仕事に望んだことは、これらのいずれかのいずれかであった


$product->carts()->detach($itemId);
または
$product->carts()->detach($cartId)->first();

私はcart_id & product_idに基づいてピボットテーブルを照会する場合は、そのクエリ結果にfirst &実行delete()を呼び出しますa Call to undefined method stdClass::delete()が返されます。

私はdd()$firstItemデータを照会した後、それが(正しい)オブジェクト

{#238 ▼ 
    +"id": 1 
    +"cart_id": 1 
    +"product_id": 1 
    +"item_id": 5 
} 
+0

を '$製品 - >カート() - > detach($ itemId); 'は動作するはずです。どのようなエラーが出ますか? – devk

+0

@devkもっと見る'$ itemId'は追加列のIDですが、' cart_id'は表示されません。 –

+0

@AlexeyMezeninああそうだ。 $ product-> carts() - >どこで( 'cart_product.item_id'、$ itemId) - > detach() 'は動作しますか?関係に ' - > withPivot(['item_id'])'があると仮定します。 – devk

答えて

1

が返されますときは、この表の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(); 
+0

その結果、未定義のメソッドへの呼び出しstdClass :: delete() – Liam

+0

'first()'、 'find()'などを使用していませんか? [構文は正しい](https://laravel.com/docs/5.3/queries#deletes) –

+0

質問を更新し、自分のコードに 'first()'を追加しました。それを削除して、私の答えのコードをそのまま使用してください。 –

関連する問題