I
I
Ilya Parshakov2018-05-09 21:33:31
Laravel
Ilya Parshakov, 2018-05-09 21:33:31

How to remove link model links?

Hello! It is impossible to delete from a DB the linking data in any way. Now I will explain.
There are 3 models: House , Flat , Room .
These models are in relationship:
- House one-to-many Flat ;
- Flat one-to-many Room .
To remove all links House in relation to Flat I use:

$house = House::find($id);
$house->flats()->delete();

But how do you remove not only that, but also the Flat relationships with respect to Room ? That is, how to remove all links that the House model has ?
I try:
$house = House::find($id);
$house->flats()->rooms()->delete();

But there is an error "Call to undefined method Builder::rooms()"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yan-s, 2018-05-09
@Yan-s

It is possible to use a foreign key and mysql ON DELETE CASCADE behavior to delete related records at the DB level.
But, in theory, your code should also work. What method are you looking for - answers()?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question