/** * 创建一条记录 * * @param array $row * 要插入的记录 * @param boolean $return_pk_values * 是否返回新建记录的主键值 * * @return array|null */ function insert(array $row, $return_pk_values = false) { if (!$this->_inited) { $this->init(); } $insert_id = array(); if ($return_pk_values) { $use_auto_incr = false; if ($this->_is_cpk) { // 假定复合主键必须提供所有主键的值 foreach ($this->_pk as $pk) { $insert_id[$pk] = $row[$pk]; } } else { // 如果只有一个主键字段,并且主键字段不是自增,则通过 nextID() 获得一个主键值 $pk = $this->_pk[0]; if (empty($row[$pk])) { unset($row[$pk]); if (!self::$_meta[$this->_cache_id][$pk]['auto_incr']) { $row[$pk] = $this->nextID($pk); $insert_id[$pk] = $row[$pk]; } else { $use_auto_incr = true; } } else { $insert_id[$pk] = $row[$pk]; } } } else { $pk = $this->_pk[0]; if (!$this->_is_cpk && !self::$_meta[$this->_cache_id][$pk]['auto_incr'] && empty($row[$pk])) { // 如果只有一个主键字段,并且主键字段不是自增,则通过 nextID() 获得一个主键值 $pk = $this->_pk[0]; $row[$pk] = $this->nextID($pk); } } $this->_conn->insert($this->getFullTableName(), $row, self::$_fields[$this->_cache_id]); if ($return_pk_values) { // 创建主表的记录成功后,尝试获取新记录的主键值 if ($use_auto_incr) { $insert_id[$pk] = $this->_conn->insertID(); } return $insert_id; } else { return null; } }