When a user wants to set an Image to be featured we want to reset all the other images to not be featured. I have this working using the following raw SQL query.
Is there a cleaner way to do this using the ORM or for this type of thing is it cleaner to keep it the way it is?
<?php
class Banner extends DataObject {
private static $db = array(
'FeaturedImage' => 'Boolean'
);
private static $has_one = array(
'Image' => 'Image'
);
private static $summary_fields = array(
'Image.CMSThumbnail' => 'Image',
'FeaturedImage.Nice' => 'Featured?'
);
public function onBeforeWrite()
{
parent::onBeforeWrite();
// When user sets an image to be featured, reset all other images not to be featured
if ($this->FeaturedImage) {
$query = 'UPDATE Banner SET FeaturedImage = 0 WHERE Banner.ID !=' . $this->ID;
DB::query($query);
}
}
}