Home > Enterprise >  Create two BelongsToMany, how do I delet only on in table?
Create two BelongsToMany, how do I delet only on in table?

Time:01-09

So I've created two Models : 'Category' and 'Product', within these tow I added function :

public function product()
{
    return $this->belongstoMany(Product::class);
}

and

 public function category()
{
    return $this->belongstoMany(Category::class);
}

and now I have in the Database : category_id and product_id

And when I create an Relation like: category_id 1 and product_id 2

How do I delete this, without deleting all enterys.

My function so far:

 $category = Category::where($request->categoryId);
$category->product()->detach();

But this acutally deletes or detaches all the enterys for the categoryId.

How do I do it now?

CodePudding user response:

Always browse the docs first =)

// IDs to be detached
$productIds = [ 1, 2, 3 ];
$category->product()->detach($productIds);

// Or single record
$category->product()->detach(2);
  •  Tags:  
  • Related