删除dataobject时删除文件

tho*_*son 0 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();                    
}

}
Run Code Online (Sandbox Code Playgroud)

小智 5

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

public function onBeforeDelete() {
    if ($this->Attachment()->exists()) {
        $this->Attachment()->delete();
    }
}
Run Code Online (Sandbox Code Playgroud)