Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove reationship from many-to-many models in laravel 4

I tried the following:

$one = OneModel::findOrFail($id);
$two = $one->two_model()->findOrFail($two_id);
$two->delete();

But that deletes the record from the database, how can I just remove the relationship without deleting from the table? And also not having to mess with the pivot table, because if that is needed, why am I even using a framework...

like image 856
localhost Avatar asked Sep 11 '13 02:09

localhost


People also ask

How do I delete a relationship in Laravel?

To delete a model directly, call delete() on it and don't define a deleting listener in its boot method or define an empty deleting method. If you want to further delete relations of a related model, you will define a deleting listener in the boot method of that model and delete the relations there.

How do you retrieve a many to many relationship?

To avoid this problem, you can break the many-to-many relationship into two one-to-many relationships by using a third table, called a join table. Each record in a join table includes a match field that contains the value of the primary keys of the two tables it joins.

What is the use of whereHas in Laravel?

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

What is many to many relationship in Laravel?

In the category_product table, you can see product_id 1 have multiple entiries with category_id 2 and 3. That's how you can create many to many relationships in Laravel Eloquent. Obviously, you can use the inverse of this relationship to attach a category to multiple products.


1 Answers

If I got you correctly, detach() is what you're looking for:

$one = OneModel::findOrFail($id);
$one->two_model()->detach($two_id);

This will delete only the relation with one_model's table's $id and two_model's table's $two_id in your pivot table.

Click here for more details.

like image 147
Arda Avatar answered Sep 20 '22 19:09

Arda