Silverstripe 删除数据对象时删除文件
我有如下'resource'数据对象,附件有一个关系。我想在删除“资源”对象时删除附件 但我得到的是一个致命错误:对中的非对象调用成员函数delete()Silverstripe 删除数据对象时删除文件,silverstripe,Silverstripe,我有如下'resource'数据对象,附件有一个关系。我想在删除“资源”对象时删除附件 但我得到的是一个致命错误:对中的非对象调用成员函数delete() <?php class Resource extends DataObject { private static $db = array ( 'Name' => 'Varchar(200)', 'Description' => 'Text', 'Category' => "Enum('Dat
<?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();
}
}
这里的问题是,假设DataObject::get\u by\u id
总是返回一个对象是不正确的。您可以先检查$file
是否为非假值,或者通过has_one getter执行所有操作,使用:
public function onBeforeDelete() {
if ($this->Attachment()->exists()) {
$this->Attachment()->delete();
}
}
这里的问题是您认为DataObject::get_by_id
总是返回一个对象的假设是不正确的。您可以先检查$file
是否为非假值,或者通过has_one getter执行所有操作,使用:
public function onBeforeDelete() {
if ($this->Attachment()->exists()) {
$this->Attachment()->delete();
}
}