示例#1
0
文件: Model.php 项目: abcarroll/DABL
 /**
  * Creates and executes INSERT query string for this object
  * @return int
  */
 protected function insert()
 {
     $conn = static::getConnection();
     $pk = static::$_primaryKey;
     $fields = array();
     $values = array();
     $placeholders = array();
     foreach (static::$_columnNames as &$column) {
         $value = $this->{$column};
         if ($value === null && !$this->isColumnModified($column)) {
             continue;
         }
         $fields[] = $conn->quoteIdentifier($column, true);
         $values[] = $value;
         $placeholders[] = '?';
     }
     $quoted_table = $conn->quoteIdentifier(static::getTableName(), true);
     $query_s = 'INSERT INTO ' . $quoted_table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $placeholders) . ') ';
     if ($pk && $this->isAutoIncrement() && $conn instanceof DBPostgres) {
         $query_s .= ' RETURNING ' . $conn->quoteIdentifier($pk, true);
     }
     $statement = new QueryStatement($conn);
     $statement->setString($query_s);
     $statement->setParams($values);
     $result = $statement->bindAndExecute();
     $count = $result->rowCount();
     if ($pk && $this->isAutoIncrement()) {
         $id = null;
         if ($conn instanceof DBPostgres) {
             $id = $result->fetchColumn(0);
         } elseif ($conn->isGetIdAfterInsert()) {
             $id = $conn->lastInsertId();
             if (empty($id) && $conn instanceof DBRedshift) {
                 $id = $conn->query('SELECT MAX(' . $conn->quoteIdentifier($pk) . ") FROM {$quoted_table}")->fetchColumn();
             }
         }
         if (null !== $id) {
             $this->{"set{$pk}"}($id);
         }
     }
     $this->resetModified();
     $this->setNew(false);
     $this->insertIntoPool($this);
     return $count;
 }