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...
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.
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.
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With