atk4\data\Reference_One::ref PHP Method

ref() public method

If owner model is not loaded, then return referenced model with condition set. This can happen in case of deep traversal $m->ref('Many')->ref('one_id'), for example.
public ref ( array $defaults = [] ) : Model
$defaults array Properties
return Model
    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;
    }