I was trying to avoid posting a whole lot of code, but here goes:
Gallery model:
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness;
class Gallery extends ModelBase {
public function initialize() {
$this->setSource('gallery');
$this->hasMany(
'id',
'GalleryImage',
'galleryId',
[
'alias' => 'images'
]
);
}
public function columnMap() {
return [
'id' => 'id',
'name' => 'name',
'slug' => 'slug',
'description' => 'description',
'rating' => 'rating'
];
}
public function validation() {
$validator = new Validation();
$validator->add('slug', new Uniqueness([
'message' => 'This slug already exists!'
]));
return $this->validate($validator);
}
}
GalleryImage model:
class GalleryImage extends ModelBase {
public function initialize() {
parent::initialize();
$this->setSource('gallery_image');
$this->belongsTo('galleryId', 'Gallery', 'id', ['alias' => 'gallery']);
}
public function columnMap() {
return [
'id' => 'id',
'gallery_id' => 'galleryId',
'title' => 'title',
'image' => 'image',
'link' => 'link'
];
}
public function beforeSave () {
$this->link = trim($this->link);
if (empty($this->link) && !is_null($this->link)) {
$this->link = NULL;
}
}
}
The Gallery model may have NULL slug, in which case gallery is not accessible on the web site. However, since Uniqueness checks NULL against other NULLs, it will fail, even though it was not the Gallery object that was being saved, rather a GalleryImage object.
The fix was to do this in the Gallery object:
public function validation() {
$validator = new Validation();
if (!empty($this->slug)) {
$validator->add('slug', new Uniqueness([
'message' => 'This slug already exists!'
]));
}
return $this->validate($validator);
}
However, I'm still puzzled why is Gallery object being validated if save is being made on GalleryImage.