我有一個稍微像這樣的應用方案:的Yii:串聯在一起,刪除相關紀錄文件
<?php
class Category extends CActiveRecord
{
public function relations()
{
return array(
'posts' => array(self::HAS_MANY, 'Post', 'category_id'),
);
}
// ...
}
class Post extends CActiveRecord
{
public function relations()
{
return array(
'categories' => array(self::BELONGS_TO, 'Category', 'category_id'),
'pictures' => array(self::HAS_MANY, 'PostPicture', 'post_id'),
);
}
// ...
}
class PostPicture extends CActiveRecord
{
public function relations()
{
return array(
'post' => array(self::BELONGS_TO, 'Post', 'post_id'),
);
}
// ... public function deleteFiles() ...
}
所有關係,在PHP代碼中定義還存在與適當的外鍵和ON DELETE CASCADE
建立數據庫( InnoDB的)。 PostPicture
提供了一種刪除關聯文件的方法。
當我通過$category->delete();
刪除Category
對象時,發生數據庫級別的ON DELETE CASCADE,圖片記錄會在我可以訪問它們之前被刪除,並且我將無法檢索文件系統路徑。
完全禁用外鍵並不是很優雅 - 我必須爲幾乎所有的模型類實現beforeDelete
鉤子。
檢索與該類別的帖子相關的所有PostPicture行,並在Category::beforeDelete()
中調用它們的deleteFiles
函數似乎是一個可接受的解決方案,但有沒有更好的方法來實現這一點?