Exemplo n.º 1
0
 /**
  * Inserts row in a table.
  * @param  array|\Traversable|Selection array($column => $value)|\Traversable|Selection for INSERT ... SELECT
  * @return ActiveRow|int|bool Returns IRow or number of affected rows for Selection or table without primary key
  */
 public function insert($data)
 {
     if ($data instanceof Selection) {
         $data = new SqlLiteral($data->getQuery(), $data->getParameters());
     } elseif ($data instanceof \Traversable) {
         $data = iterator_to_array($data);
     }
     $return = $this->connection->query($this->getSqlBuilder('insert')->getQuery(), $data);
     $this->loadRefCache();
     if ($data instanceof SqlLiteral || $this->primary === null) {
         unset($this->refCache['referencing'][$this->getGeneralCacheKey()][$this->getSpecificCacheKey()]);
         return $return->getRowCount();
     }
     $primaryKey = $this->connection->getInsertId($this->getPrimarySequence());
     if ($primaryKey === false) {
         unset($this->refCache['referencing'][$this->getGeneralCacheKey()][$this->getSpecificCacheKey()]);
         return $return->getRowCount();
     }
     if (is_array($this->getPrimary())) {
         $primaryKey = array();
         foreach ((array) $this->getPrimary() as $key) {
             if (!isset($data[$key])) {
                 return $data;
             }
             $primaryKey[$key] = $data[$key];
         }
         if (count($primaryKey) === 1) {
             $primaryKey = reset($primaryKey);
         }
     }
     $row = $this->createSelectionInstance()->wherePrimary($primaryKey)->fetch();
     if ($this->rows !== NULL) {
         if ($signature = $row->getSignature(false)) {
             $this->rows[$signature] = $row;
             $this->data[$signature] = $row;
         } else {
             $this->rows[] = $row;
             $this->data[] = $row;
         }
     }
     return $row;
 }