如何检测图像文件名是否已更改?
How to detect if Image Filename has changed?
我需要检查图像的文件名是否已更改,如果已更改,则我需要更新 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;
}
}
}
这不起作用的原因是你的 onBeforeWrite
在保存 TourPhoto
时被调用,而不是在你的 Image
被保存时调用。 Name
在保存 Image
时更改。
你可以尝试两件事。添加一个带有 onBeforeWrite
的 Image
扩展,您可以在其中获取 TourPhotos
那个 link 到您的图像并更新它们的 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;
}
}
}
我需要检查图像的文件名是否已更改,如果已更改,则我需要更新 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;
}
}
}
这不起作用的原因是你的 onBeforeWrite
在保存 TourPhoto
时被调用,而不是在你的 Image
被保存时调用。 Name
在保存 Image
时更改。
你可以尝试两件事。添加一个带有 onBeforeWrite
的 Image
扩展,您可以在其中获取 TourPhotos
那个 link 到您的图像并更新它们的 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;
}
}
}