/** * @param array $data * @param bool $deep * @param bool $mapVirtualFields */ public function fromArray(array $data, $deep = true, $mapVirtualFields = false) { $exists = isset($data[self::FROM_ARRAY_EXISTS_KEY]) && $data[self::FROM_ARRAY_EXISTS_KEY] === true; $relationReferences = array(); foreach ($data as $name => $value) { if ($this->_table->hasField($name)) { $this->set($name, $value); } else { if ($this->_table->hasRelation($name)) { if ($deep) { $relationReferences[$name] = $value; } } else { if ($mapVirtualFields) { $this->mapValue($name, $value); } } } } if ($exists) { $this->_exists = true; $this->refresh(); } if ($relationReferences) { $this->setRelatedFromArray($relationReferences, $mapVirtualFields); } }
/** * Insert row * TODO unit test it! * * @param Table $table * @param array $fields * @return int */ public function insert(Table $table, array $fields) { $columns = array(); $values = array(); $params = array(); $identifierFields = $table->getIdentifierFields(); $identifier = array(); foreach ($fields as $fieldName => $value) { if (!$table->hasField($fieldName)) { continue; } $columns[] = $this->quoteIdentifier($fieldName); if ($value instanceof Expression) { $values[] = $value->getSql(); } else { $values[] = '?'; $params[] = $value; if ($value !== null && in_array($fieldName, $identifierFields, true)) { $identifier[$fieldName] = $value; } } } // build query $query = 'INSERT INTO ' . $this->quoteIdentifier($table->getTableName()) . ' (' . implode(', ', $columns) . ')' . ' VALUES (' . implode(', ', $values) . ')'; if (count($identifier) !== count($identifierFields)) { $identifier = array(); } $this->dispatchRowEvent(self::EVENT_PRE_INSERT, $table, $fields, $identifier); $this->lastInsertId[$table->getTableName()] = null; $affectedRows = $this->exec($query, $params); $this->lastInsertId[$table->getTableName()] = $this->getLastInsertId($table->getTableName()); if (empty($identifier) && count($identifierFields) == 1) { $identifier[$identifierFields[0]] = $this->getLastInsertId($table->getTableName()); } $this->dispatchRowEvent(self::EVENT_POST_INSERT, $table, $fields, $identifier); return $affectedRows; }