Example #1
0
 /**
  * ref() will traverse reference and will attempt to load related model's entry. If the entry will fail to load
  * it will return model which would not be loaded. This can be changed by specifying an argument:.
  *
  * 'model' - simply create new model and return it without loading anything
  * false or 'ignore' - will not even try to load anything
  * null (default) - will tryLoad()
  * 'load' - will always load the model and if record is not present, will fail
  * 'create' - if record fails to load, will create new record, save, get ID and insert into $this
  * 'link' - if record fails to load, will return new record, with appropriate afterSave hander, which will
  *          update current model also and save it too.
  *
  * @param string|bool|null $mode
  *
  * @return Model
  */
 public function ref($mode = null)
 {
     if ($mode == 'model') {
         return $this->add($this->model_name);
     }
     $this->getModel()->unload();
     if ($mode === false || $mode == 'ignore') {
         return $this->model;
     }
     if ($mode == 'load') {
         return $this->model->load($this->get());
     }
     if ($mode === null) {
         if ($this->get()) {
             $this->model->tryLoad($this->get());
         }
         return $this->model;
     }
     if ($mode == 'create') {
         if ($this->get()) {
             $this->model->tryLoad($this->get());
         }
         if (!$this->model->loaded()) {
             $this->model->save();
             $this->set($this->model->id);
             $this->owner->save();
             return $this->model;
         }
     }
     if ($mode == 'link') {
         /** @type Model $m */
         $m = $this->add($this->model_name);
         if ($this->get()) {
             $m->tryLoad($this->get());
         }
         $t = $this;
         if (!$m->loaded()) {
             $m->addHook('afterSave', function ($m) use($t) {
                 $t->set($m->id);
                 $t->owner->saveLater();
             });
         }
         return $m;
     }
 }