C
C
chelkaz2016-10-15 16:09:46
Laravel
chelkaz, 2016-10-15 16:09:46

Why is the associated record not being deleted in the table?

There are 3 tables:
pictures , sections and catalogs The catalog
model is related to belongsTo with pictures and hasMany with sections So it makes sense that a catalog can have photos and many sections. Sections, in turn, can also have a photo and the section model is also associated with the belongsTo photo and another section belongs to the directory, so to find out which one I added to the section model and belongsTo to the directory. But the problem with the removal, I added to the events according to the documentation in the AppServiceProvider for the sections:



Section::deleting(function ($section) {
            $section->pictures()->delete();
        });

И при удалении разделов удаляется и фото, все работает верно.
Но вот если я удаляю каталог, то нужно что бы фото каталога, разделы и фото разделов удалились, которые связаны с этим каталогом. Я сделал так:
В AppServiceProvider добавил
public function boot()
    {
        // Удаляем фото при удалении раздела
        Section::deleting(function ($section) {
            $section->pictures()->delete();
        });
       // Удаляем каталог и его фото и разделы и фото разделов при удалении каталога
        Catalog::deleting(function ($catalog) {
            $catalog->pictures()->delete();
            $catalog->sections()->delete();
        });
    }

Но в итоге фото разделов остаются в таблице при удалении каталога... Что я не так делаю, и вообще логика верна?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WebDev, 2016-10-15
@kirill-93

При правильной настроке отношений, записи в AppServiceProvider не нужны. Все связанные записи удаляются автоматически.
У каталога должно быть hasMany отношение к картинкам, ведь картинки принадлежат каталогу.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question