public function ref($defaults = [])
{
$m = $this->getModel($defaults);
// add hook to set our_field = null when record of referenced model is deleted
$m->addHook('afterDelete', function ($m) {
$this->owner[$this->our_field] = null;
});
// if owner model is loaded, then try to load referenced model
if ($this->their_field) {
if ($this->owner[$this->our_field]) {
$m->tryLoadBy($this->their_field, $this->owner[$this->our_field]);
}
return $m->addHook('afterSave', function ($m) {
$this->owner[$this->our_field] = $m[$this->their_field];
});
} else {
if ($this->owner[$this->our_field]) {
$m->tryLoad($this->owner[$this->our_field]);
}
return $m->addHook('afterSave', function ($m) {
$this->owner[$this->our_field] = $m->id;
});
}
// can not load referenced model or set conditions on it, so we just return it
return $m;
}