Inserts to table from different query.
Warning: silently discards remote aliases if not existing as local column.
@param App_Model_Db_Mysql $model
@return App_Model_Db_Mysql
19457
public function insertFrom($model)
	{
		$db = $this->getDb();
		$myCols = array_keys( $this->schemaColumnsGet() );
		$theirCols = $model->getColumnAliases();
		$columns = '('.implode( ',', array_map_val( array_intersect( $theirCols, $myCols ), $this->quoteColumnDg() ) ).')';
		$table = $this->quoteTable();
		$db->exec('INSERT INTO '.$table.' '.$columns.' '.$model->getSQL());
		$this->id = $this->getLastInsertId();
		if( $this->recordExists() )
		{
			return $this->filterById($this->id)->loadOne();
		}
		else
		{
			return $this;
		}
	}
564581
protected function insertModelAsLastChildOf(Model &$model, Model &$parent)
    {
        if ($parent->isNew())
            throw new Exception('Parent model should be saved before child insert');

        /** @var \T4\Orm\Model $class */
        $class = get_class($model);
        $tableName = $class::getTableName();
        /** @var \T4\Dbal\Connection $connection */
        $connection = $class::getDbConnection();

        if (!$model->isNew()) {
            $model->refreshTreeColumns();
            $this->removeFromTreeByElement($model);
        }
        $parent->refreshTreeColumns();

        $width = $model->getTreeWidth();

        $query = (new Query("
            UPDATE " . $tableName . "
            SET __rgt = __rgt + :width + 1
            WHERE __rgt >= :rgt
            "))
            ->params([':width' => $width, ':rgt' => $parent->__rgt]);
        $connection->execute($query);

        $query = (new Query("
            UPDATE " . $tableName . "
            SET __lft = __lft + :width + 1
            WHERE __lft > :rgt
            "))
            ->params([':width' => $width, ':rgt' => $parent->__rgt]);
        $connection->execute($query);

        $model->__lft = $parent->__rgt;
        $model->__rgt = $parent->__rgt + $width;
        $model->__lvl = $parent->__lvl + 1;
        $model->__prt = $parent->getPk();

        $parent->__rgt += $width + 1;

    }
582099
public function insertNode($model)
    {
        $this->validate(['model' => $model]);
        $query = null;

        $data = $this->con->getData($model, $query);
        
        $params = [
            'index' => $this->client->getIndex(),
            'type'  => $model->tableName(),
            'id'    => $data[0][$this->idColumn],
            'body'  => $data[0]
        ];
        $responses = $this->client->getClient()->index($params);
        return $responses['result'];
    }
755445
function Insert($model){

        $this->OpenTransaction();

        $data = clone $model;

        $table = $this->getTableName($data);

        //verifico se é um objeto
        if (is_object($data))
            ModelState::ModelTreatment($data);

        $data = (array)$data;


        // Ordena
        ksort($data);

        // Campos e valores
        $camposNomes = implode('`, `', array_keys($data));
        $camposValores = ':' . implode(', :', array_keys($data));


        // Prepara a Query
        $sth = $this->prepare("INSERT INTO $table (`$camposNomes`) VALUES ($camposValores)");

        // Define os dados
        foreach ($data as $key => $value) {
            // Se o tipo do dado for inteiro, usa PDO::PARAM_INT, caso contr�rio, PDO::PARAM_STR
            $tipo = (is_int($value)) ? \PDO::PARAM_INT : \PDO::PARAM_STR;

            // Define o dado
            $sth->bindValue(":$key", $value, $tipo);
        }

        // Executa
        try {
            $sth->execute();
        }catch (\Exception $e){
            echo $e->getMessage();
        }

        $primaryKey = ModelState::GetPrimary($model);
        if(!empty($primaryKey))
            $model->$primaryKey = $this->lastInsertId();
        return $this->lastInsertId();
    }
261262
protected function newModelQuery($model = null)
    {
        return is_null($model)
                ? $this->createModel()->newQuery()
                : $model->newQuery();
    }
310550
protected function getModelTable($model)
    {
        if (!is_object($model)) {
            $model = new $model;
        }

        return DB::getTablePrefix().$model->getTable();
    }
651622
public function dropTable(ModelInterface $model)
    {
        $i = 0;

        $model->setConnection($this->connection);

        $builder = $this->getQueryBuilder();

//        $this->connection->executeUpdate($adapter->sqlCheckIntegrity(false, 'public', $model->tableName()));

        $schemaManager = $this->connection->getSchemaManager();
        foreach ($model->getMeta()->getManyToManyFields() as $field) {
            if (null === $field->through) {
                $fieldTable = TableNameResolver::getTableName($field->getTableName());
                if ($this->hasTable($fieldTable)) {
                    $schemaManager->dropTable($builder->getQuotedName($fieldTable));
                    $i += 1;
                }
            }
        }

        if ($this->hasTable($model->tableName())) {
            $schemaManager->dropTable($model->tableName());
            $i += 1;
        }

//        $this->connection->executeUpdate($adapter->sqlCheckIntegrity(true, 'public', $model->tableName()));

        return $i;
    }
50188
public function createClonedModel($model)
    {
        $clone = clone $model;
        $clone->setId(null);

        $environment  = $this->getEnvironment();
        $properties   = $environment->getDataDefinition()->getPropertiesDefinition();
        $dataProvider = $environment->getDataProvider($clone->getProviderName());

        foreach (\array_keys($clone->getPropertiesAsArray()) as $propName) {
            // If the property is not known, remove it.
            if (!$properties->hasProperty($propName)) {
                continue;
            }

            $property = $properties->getProperty($propName);
            $this->handleClonedModelProperty($clone, $property, $dataProvider);
        }

        return $clone;
    }
1325266
protected function makeGenericUpdate(Model $model)
	{
		// Get first fillable key that is not the models primary key.
		$field = array_first(
			$model->getFillable(), function ($key, $value) use ($model) {
			return ($value !== $model->getKeyName());
		}
		);

		switch (gettype($model->{$field})) {
			case 'string':
				$model->{$field} = $model->{$field} . ' updated';
				break;
			case 'boolean':
				$model->{$field} = ! $model->{$field};
				break;
			case 'integer':
			case 'NULL':
			default:
				$model->{$field} = $model->{$field} + 1;
		}

		return $this;
	}
839526
public function save(Model $model) {
        if ($model->isPrimaryKey($this->foreignKey)) {
            $model->save();
            $this->parent->{$this->localKey} = $model->{$this->foreignKey};
            $this->parent->save();
            return $this;
        }
        $model->{$this->foreignKey} = $this->parent->{$this->localKey};
        $model->save();
        return $this;
    }
1110602
public function insertLocalModel($model, $replacements = array()){
		$model = str_replace('LOCAL_NAMESPACE#', $this->localNs, $model);
		$model = str_replace('{ROOT_PATH}', ROOT_PATH, $model);
		
		foreach ($replacements as $k => $r){
			$model = str_replace($k, $r, $model);
		}

		return $this->insertModel($this->localNs, $model);
	}
825210
public function beforeSave(Model &$model)
    {

        if ($model->isNew()) {
            if (empty($model->parent)) {
                $this->insertModelAsLastRoot($model);
            } else {
                $this->insertModelAsLastChildOf($model, $model->parent);
            }
        } else {
            /** @var \T4\Orm\Model $class */
            $class = get_class($model);
            $oldParent = empty($model->__prt) ? null : $class::findByPk($model->__prt);
            if ($oldParent != $model->parent) {
                $model->refreshTreeColumns();
                if (empty($model->parent)) {
                    $this->insertModelAsLastRoot($model);
                } else {
                    /** @var \T4\Dbal\Connection $connection */
                    $connection = $class::getDbConnection();
                    $query = new Query();
                    $query
                        ->select('count(*)')
                        ->from($class::getTableName())
                        ->where('__id=:id AND __lft>:lft AND __rgt<:rgt')
                        ->params([':id' => $model->parent->getPk(), ':lft'=>$model->__lft, ':rgt'=>$model->__rgt]);

                    if ($connection->query($query)->fetchScalar() > 0) {
                        throw new Exception('Parent must not be in children!');
                    }

                    $this->insertModelAsLastChildOf($model, $model->parent);
                }
            }
        }

        return true;

    }
571776
public function joinFrom($model, $thisKeyCol, $thatKeyCol=null, $conditions='')
	{
		if( $thatKeyCol===null )
		{
			debug_assert( $thisKeyCol!==null );
			$thatKeyCol = $model->getPrimaryKey();
		}
		elseif( $thisKeyCol===null )
		{
			debug_assert( $thatKeyCol!==null );
			$thisKeyCol = $this->getPrimaryKey();
		}

		$this->prefixColumn($model, $thatKeyCol);
		$this->prefixColumn($this, $thisKeyCol);

		$conditions = str_replace('{that}', $model->getAlias(), $conditions);
		$conditions = str_replace('{this}', $this->getAlias(), $conditions);

		$this->mapPartWhere( $this->addAliasToConditionDg() );
		$model->mapPartWhere( $model->addAliasToConditionDg() );

		$thisFrom = $this->_select->getPart(Zend_Db_Select::FROM);
		$modelColumns = array_chain(
			$model->_select->getPart(Zend_Db_Select::COLUMNS),
			array_group_dg( array_get_dg(return_dg(0)) ),
			array_map_val_dg(
				array_chain_dg(
					array_map_val_dg(
						function($descriptor)
						{
							return null===$descriptor[2]
								? $descriptor[1]
								: [ $descriptor[2] => $descriptor[1] ]
							;
						}
					),
					function($columns){
						$outArray = [];
						array_map_val($columns, function($column)use(&$outArray){
							if(is_array($column))
							{
								array_map_val($column, function($column, $alias)use(&$outArray){
									$outArray[$alias] = $column;
								});
							}
							else
							{
								$outArray[] = $column;
							}
						});
						
						return $outArray;
					}
				)
			)
		);

		array_each(
			$model->_select->getPart(Zend_Db_Select::FROM),
			function( $descriptor, $alias )use($modelColumns,$thisFrom,$model,$thisKeyCol,$thatKeyCol,$conditions)
			{
				debug_enforce(
					!array_key_exists( $alias, $thisFrom ),
					"Alias `{$alias}` already used for table `{$descriptor['tableName']}`"
				);

				switch( $descriptor['joinType'] )
				{
					case Zend_Db_Select::FROM:
						$this->_select->joinLeft(
							[$model->getAlias()=>$model->getTable()],
							"{$thisKeyCol}={$thatKeyCol} ".$conditions,
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor[ 'schema' ]
						);
					break;
					case Zend_Db_Select::INNER_JOIN:
						$this->_select->joinInner(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::LEFT_JOIN:
						$this->_select->joinLeft(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::RIGHT_JOIN:
						$this->_select->joinRight(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::FULL_JOIN:
						$this->_select->joinFull(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::CROSS_JOIN:
						$this->_select->joinCross(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					case Zend_Db_Select::NATURAL_JOIN:
						$this->_select->joinNatural(
							[$alias=>$descriptor['tableName']],
							$descriptor['joinCondition'],
							array_key_exists( $alias, $modelColumns ) ? $modelColumns[ $alias ] : [],
							$descriptor['schema']
						);
					break;
					default:
						debug_assert( false, "Unknown join type ".var_dump_human_compact($descriptor['joinType']));
					break;
				}
			}
		);

		$this->settingsJoin($model);

		return $this;
	}
1201351
public function createModel($model)
    {
        $schema = new Schema();

        $tableDef = $schema->createTable($model->getMeta()->getDbTable());
        // this assumes fields set_from_name has been invoked
        $primaryKeyFields = [];
        $unique_fields = [];
        $indexes = [];
        /** @var $field Field */
        /** @var $field ForeignKey */
        foreach ($model->getMeta()->localFields as $fname => $field) {
            $colName = $field->getColumnName();
            $type = $field->dbType($this->connection);
            // if we don't have a type skip
            if (empty($type)) {
                continue;
            }
            if ($field->primaryKey) {
                $primaryKeyFields[] = $model->getMeta()->primaryKey->getColumnName();
            } elseif ($field->isUnique()) {
                $unique_fields[] = $colName;
            } elseif ($field->dbIndex) {
                $indexes[] = $colName;
            }
            $tableDef->addColumn($colName, $type, $this->getDoctrineColumnOptions($field));
            if ($field->isRelation && $field->relation && $field->dbConstraint) {
                $relField = $field->getRelatedField();
                $tableDef->addForeignKeyConstraint(
                    $relField->scopeModel->getMeta()->getDbTable(),
                    [$field->getColumnName()],
                    [$relField->getColumnName()]
                );
            }
        }
        // create the primary key
        $tableDef->setPrimaryKey($primaryKeyFields);
        // add index constraint
        if (!empty($indexes)) {
            $tableDef->addIndex($indexes);
        }
        // add unique constraint
        if (!empty($unique_fields)) {
            $tableDef->addUniqueIndex($unique_fields);
        }
        $this->createTable($tableDef);
        // many to many
        /** @var $relationField ManyToManyField */
        foreach ($model->getMeta()->localManyToMany as $name => $relationField) {
            if ($relationField->manyToMany && $relationField->relation->through->getMeta()->autoCreated) {
                $this->createModel($relationField->relation->through);
            }
        }
    }
342015
public function unlink(Model $model) {
        $this->getUnlinked()->flush()->append($model);

        $this->getPrimaryModel()->set($this->getPrimaryForeignKey(), null);

        return $this;
    }
361980
function insert (model) {
    var insert = model.insertDelayed && model.engine === 'MyISAM' ? 'INSERT DELAYED' : 'INSERT'
    var columns = _.map(model.insertColumnNames, quoteName).join(', ')
    var values = _.map(model.insertColumnNames, columnName => placeholder(model, columnName, model.columns[columnName])).join(', ')
    return `${insert} INTO ${quoteName(model.name)} (${columns}) VALUES(${values})`
}
1077456
public static function query($alias = null, $model = null)
    {
        if (!$model) {
            $model = Di::getDefault()->getShared(static::class);
        }

        $query = $model->_di->get('ManaPHP\Db\Query')->setModel($model);
        if ($alias) {
            $query->from(get_class($model), $alias);
        }

        return $query;
    }