我有'Resouce‘数据对象,如下所示,附件作为has_one关系。当“资源”对象被删除时,我想删除附件。
但是我得到的是致命错误:调用非对象的成员函数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();
}
}发布于 2014-08-06 11:54:48
这里的问题是假设DataObject::get_by_id总是返回一个对象是不正确的。您可以首先检查$file是一个非假值,也可以通过has_one getter执行所有操作,使用:
public function onBeforeDelete() {
if ($this->Attachment()->exists()) {
$this->Attachment()->delete();
}
}https://stackoverflow.com/questions/25157102
复制相似问题