Example #1
0
 /**
  * insert new, or update existed
  */
 public function save()
 {
     if (!$this->isPersistable) {
         throw new \LogicException("This object is not persistable (may be it loaded with aggregation)");
     }
     if ($this->eventDispatch(self::EVENT_BEFORE_SAVE)) {
         if ($this->isNewRecord) {
             $data = $this->data;
             if ($this->metadata->pk->auto_increment) {
                 unset($data[$this->metadata->pk->db_column]);
                 $newPK = static::objects()->doInsert($data);
                 $this->data[$this->metadata->getPrimaryKey()] = $newPK;
                 if (empty($newPK)) {
                     $this->isPersistable = false;
                 }
             } else {
                 static::objects()->doInsert($data);
             }
         } else {
             $updData = $this->getChangedValues();
             //unset($updData[$this->metadata->pk->db_column]);
             if (count($updData) > 0) {
                 static::objects()->filter(['pk' => $this->pk])->doUpdate($updData);
             } else {
                 return;
             }
         }
         $this->eventDispatch(self::EVENT_AFTER_SAVE);
         $this->isNewRecord = false;
         // with this we can tell in EVENT_AFTER_SAVE was it update or insert action
         $this->cleanData = $this->data;
     }
 }
Example #2
0
 /**
  * @param $arguments
  * @return Model
  * @throws \InvalidArgumentException
  * @throws \RuntimeException
  */
 public function get($arguments)
 {
     if (is_int($arguments)) {
         $pk = $this->metadata->getPrimaryKey();
         $arguments = [$pk => intval($arguments)];
     } elseif (!is_array($arguments)) {
         throw new \InvalidArgumentException('$arguments must be int or array');
     }
     $result = $this->filter($arguments)->limit(1)->current();
     if (!$result) {
         throw new \RuntimeException('Not found');
     }
     return $result;
 }