删除dataobject时删除文件

时间:2014-08-06 09:45:43

标签: silverstripe

我有'Resouce'数据对象如下所示,附件为has_one关系。我想在删除'resource'对象时删除附件。

但我得到的是致命错误:在

中的非对象上调用成员函数delete()
<?php 
class Resource extends DataObject
{ 
private static $db = array (
    'Name' => 'Varchar(200)',
    'Description' => 'Text',
    'Category' => "Enum('Data, Drafts, Drawings, Reports, Images, Other')",
    'SortOrder' => 'Int'
);

private static $has_one = array (
    'Attachment' => 'File',
    'ResourcePage' => 'ResourcePage'
);


public function onBeforeDelete()
{
    $myAttachment = $this->Attachment();
    $file = DataObject::get_by_id('File', $myAttachment->ID); //we have to make sure it is a Dataobject object      
    $file->delete();
    $file->destroy();       
    return parent::onBeforeDelete();                    
}

}

1 个答案:

答案 0 :(得分:5)

这里的问题是你假设DataObject::get_by_id总是返回一个对象是不正确的。你可以先检查$file是否为非假值,或者只是通过has_one getter执行所有操作,使用:

public function onBeforeDelete() {
    if ($this->Attachment()->exists()) {
        $this->Attachment()->delete();
    }
}