fuel / orm

Fuel PHP Framework - Fuel v1.x ORM
http://fuelphp.com/docs/packages/orm/intro.html
151 stars 95 forks source link

Model::delete() and related models with conditions #376

Closed cuphalfempty closed 9 years ago

cuphalfempty commented 9 years ago

I have Model_Page and Model_Section which belongs Model_Page.

# classes/model/page.php
protected static $_has_many = [
    'sections' => [
        'key_from' => 'id',
        'model_to' => '\Model_Section',
        'key_to' => 'page_id',
        'cascade_save' => true,
        'cascade_delete' => true,
        'conditions' => [
            'where' => [
                ['status', 1],
            ],
        ],
    ],
];

Page::delete() removes only sections that match condition, which breaks data consistency (abandoned sections).

Do we need condition when deleting related models (belongs_to)?

WanWizard commented 9 years ago

Conditions on a relation act like a (permanent) filter, so in that sense you could say this behaviour is consistent, only records are deleted that can be fetched.

Assuming that your status can be 0 or 1, you could define three relations, active_sections (status is 1), inactive_sections (status is 0) and all_sections (no conditions).

And if you want to delete all, you should use the all_sections relation to fetch them, and subsequently delete them.

cuphalfempty commented 9 years ago

Suggested by option name - _cascadedelete - I expected (wished for) it works like MySQL ON DELETE CASCADE.

Thanks for explanation @WanWizard

WanWizard commented 9 years ago

Well, cascade_delete does work like that. But it respects the filter you have defined on the relation.