Beispiel #1
0
 /**
  * Insert
  *
  * @param  array $set
  * @return int
  */
 public function insert($set)
 {
     if (!$this->isInitialized) {
         $this->initialize();
     }
     $insert = $this->sql->insert();
     $insert->values($set);
     return $this->executeInsert($insert);
 }
Beispiel #2
0
 /**
  * Save
  *
  * @param bool $ignoreValidation
  * @return int
  * @throws Exception\ValidateException
  */
 public function save($ignoreValidation = false)
 {
     $this->initialize();
     $on = $this->rowExistsInDatabase() ? self::ON_UPDATE : self::ON_CREATE;
     // autofill empty sets
     if (!empty($this->autofills[$on])) {
         foreach ($this->autofills[$on] as $column => $autofill) {
             if (!isset($this->columns[$column]) || $this->isModified($column) || !$this->isNull($column)) {
                 continue;
             }
             $this->set($column, is_callable($autofill) ? $autofill($column, $this) : $autofill);
         }
     }
     // validate data
     if (!$ignoreValidation && !$this->isValid(true)) {
         $invalidColumn = reset($this->invalidColumns);
         throw new Exception\ValidateException($this->getValidatorChain($invalidColumn)->getFirstMessage());
     }
     // get modified data
     $data = $this->getModified();
     if (empty($data)) {
         return 0;
     }
     if ($this->rowExistsInDatabase()) {
         // UPDATE
         $where = $this->processPrimaryKeyWhere();
         $statement = $this->sql->prepareStatement($this->sql->update()->set($data)->where($where));
         $result = $statement->execute();
         $rowsAffected = $result->getAffectedRows();
         unset($statement, $result);
         // cleanup
     } else {
         // INSERT
         $insert = $this->sql->insert();
         $insert->values($data);
         $statement = $this->sql->prepareStatement($insert);
         $result = $statement->execute();
         if (($primaryKeyValue = $result->getGeneratedValue()) && count($this->primaryKey) == 1) {
             $this->primaryKeyData = array($this->primaryKey[0] => $primaryKeyValue);
         } else {
             // make primary key data available so that $where can be complete
             $this->processPrimaryKeyData();
         }
         $rowsAffected = $primaryKeyValue;
         unset($statement, $result);
         // cleanup
     }
     // refresh data
     $this->refresh();
     // return rows affected
     return $rowsAffected;
 }