我需要检查我的图像的文件名是否已更改,如果是,那么我需要更新Slug
数据库字段。我在onBeforeWrite()
内尝试了以下内容,但它似乎没有检测到这种变化。
<?php
class TourPhoto extends DataObject {
private static $db = array(
'Slug' => 'Varchar(255)'
);
private static $has_one = array(
'Image' => 'Image',
);
public function onBeforeWrite() {
parent::onBeforeWrite();
if ($this->Image()->isChanged('Name')) {
// Update slug in here...
$this->Slug = $this->Image()->Name;
}
}
}
答案 0 :(得分:2)
这不起作用的原因是,只要保存onBeforeWrite
,就会调用TourPhoto
,而不是在保存Image
时。保存Name
时会更改Image
。
你可以尝试两件事。添加一个Image
扩展程序,其中包含onBeforeWrite
,其中您将获取链接到您的图片的TourPhotos
并更新其slug。
这样的事情:
class ImageExtension extends DataExtension
{
private static $has_many = array(
'TourPhotos' => 'TourPhoto'
);
public function onBeforeWrite()
{
parent::onBeforeWrite();
if ($this->owner->isChanged('Name')) {
foreach ($this->owner->TourPhotos() as $tourPhoto) {
$tourPhoto->Slug = $this->owner->Name;
$tourPhoto->write();
}
}
}
}
然后在mysite/config.yml
Image:
extensions:
- ImageExtension
或者您可以让TourPhoto
onBeforeWrite
检查slug是否与文件名不同,然后更新它。
class TourPhoto extends DataObject
{
private static $db = array(
'Slug' => 'Varchar(255)'
);
private static $has_one = array(
'Image' => 'Image'
);
public function onBeforeWrite()
{
parent::onBeforeWrite();
if ($this->Image()->exists() && $this->Slug != $this->Image()->Name) {
$this->Slug = $this->Image()->Name;
}
}
}