I have a simple DB with multiple tables and relationships, ie: Article - Category User - Group etc...
I have implemented SoftDelete behavior where there is a Active column and if set to 0, it is considered deleted. My question is simple.
How to i specify in as few places as possible that i only want load Articles that belong to Active categories.
I have specified relationships and default scopes (with Active = 1) condition.
However, when i do findAll(), it returns those Articles that have Active = 1, even if the category it belongs to is Active = 0....
Thank you
Implementation so far: In base class
public function defaultScope()
{
return array('condition' => 'Active = 1');
}
in model:
'category' => array(self::BELONGS_TO, 'Category', 'CategoryID'),
'query':
$data = Article::model()->findAll();
MY SOLUTION
So i decided, that doing it in framework is:
- inneficient
- too much work
- not good as it moves business logic away from database - this is fairly important to save work later on when working on interfaces/webservices and other customizations that should be part of the product.
Overall lesson: Try to keep all business logic as close to database as possible to prevent disrepancies.
First, i was thinking using triggers that would propagate soft delete down the hierarchy. However after thinking a bit more i decided not to do this. The reason is, that this way if I (or an interface or something) decided to reactivate the parent records, there would be no way to say which child record was chain-deleted and which one was deleted before: CASE: Lets say Category and Article. First, one article is deleted. Then the whole category is deleted. Then you realize this was a mistake and you want to undelete the Category. How do you know which article was deleted by deleting category and which one should stay deleted? Yes there are solutions, ie timestamps but ...... too complex, too easy to break
So my solution in the end are: VIEWS. I think i will move away from yii ORM to using views for anything more complex then basic things.
There are two advantages to this for me: 1) as a DBA i can do better SQL faster 2) logic stays in database, in case the application changes/another one is added, there is no need to implement the logic in more then one places