updateByPk

Update a record and fetch it with its new values. If no records match
the given key, null is returned.

@access public
@param  array          $primary_key
@param  array          $updates
@throws ModelException
@return FlexibleEntityInterface
177453
public function updateByPk(array $primary_key, array $updates)
    {
        $where = $this
            ->checkPrimaryKey($primary_key)
            ->getWhereFrom($primary_key)
            ;
        $parameters = $this->getParametersList($updates);
        $update_strings = [];

        foreach ($updates as $field_name => $new_value) {
            $update_strings[] = sprintf(
                "%s = %s",
                $this->escapeIdentifier($field_name),
                $parameters[$field_name]
            );
        }

        $sql = strtr(
            "update :relation set :update where :condition returning :projection",
            [
                ':relation'   => $this->getStructure()->getRelation(),
                ':update'     => join(', ', $update_strings),
                ':condition'  => (string) $where,
                ':projection' => $this->createProjection()->formatFieldsWithFieldAlias(),
            ]
        );

        $iterator = $this->query($sql, array_merge(array_values($updates), $where->getValues()));

        if ($iterator->isEmpty()) {
            return null;
        }

        return $iterator->current()->status(FlexibleEntityInterface::STATUS_EXIST);
    }
250821
def update(self):
        """"""
        ret = True
        fields = self.depopulate(True)
        q = self.query
        q.set_fields(fields)

        pk = self.pk
        if pk:
            q.is_field(self.schema.pk.name, pk)

        else:
            raise ValueError("You cannot update without a primary key")

        if q.update():
            fields = q.fields
            self._populate(fields)

        else:
            ret = False

        return ret
1107759
private function update($model, $sortableAttribute, $sortOrderData)
	{
		$pk = $model->tableSchema->primaryKey;
		$pk_array = array();
		if(is_array($pk)) { // composite key
			$string_ids = array_keys($sortOrderData);
			
			$array_ids = array();
			foreach ($string_ids as $string_id)
				$array_ids[] = explode(',', $string_id);
			
			foreach ($array_ids as $array_id)
				$pk_array[] = array_combine($pk, $array_id);
		} else { // normal key
			$pk_array = array_keys($sortOrderData);
		}
		
		$models = $model->model()->findAllByPk($pk_array);
		$transaction = Yii::app()->db->beginTransaction();
		try {
			foreach ($models as $model) {
				$_key = is_array($pk) ? implode(',', array_values($model->primaryKey)) : $model->primaryKey;
				$model->{$sortableAttribute} = $sortOrderData[$_key];
				$model->save();
			}
			$transaction->commit();
		}
		catch(Exception $e) { // an exception is raised if a query fails
			$transaction->rollback();
		}
	}
236150
public function hasMany(string $related, string $primary_key = '', string $foreign_key = '')
    {
        $relatedModel = app()->make($related);
        $local_key = $local_key ?? $this->getKey();
        // Make the table name singular and append ID to it
        // FIXME: Use a more reliable approach
        $foreign_key = $foreign_key ?? rtrim($relatedModel->getTable(), 's').'_id';
        return new HasMany($relatedModel, $this, $primary_key, $foreign_key);
    }
269955
public function update($model_or_id, $update_vars, $mongo_options=[]) {
        $id = $this->extractID($model_or_id);

        $update_vars = $this->onUpdate_pre($update_vars, $model_or_id);

        $sql = $this->buildUpdateStatement($update_vars, ['id']);

        $sth = $this->connection_manager->executeWithReconnect(function($mysql_dbh) use ($sql, $update_vars, $id) {
            $sth = $mysql_dbh->prepare($sql);
            $vars = $this->removeMysqlLiterals(array_values($update_vars));
            $vars[] = $id;
            $result = $sth->execute($vars);
            return $sth;
        });

        return $sth->rowCount();
    }
717918
public function postUpdate()
    {
        $search = array();
        $replace = array();
        $dbPattern = array();
        $model = null;
        $j = 0;

        $components = Kwf_Component_Data_Root::getInstance()
            ->getComponentsByClass('Kwc_Columns_Component', array('ignoreVisible' => true));
        if (count($components) > 50) {
            echo "Kwc_Columns_Update_1: updating ".count($components)." components, this might take some time\n";
        }
        foreach ($components as $c) {
            if (!$model) $model = $c->getComponent()->getChildModel();
            $totalColumns = (int)substr($c->getComponent()->getRow()->type, 0, 1);

            $select = new Kwf_Model_Select();
            $select->whereEquals('component_id', $c->dbId);
            if ($model->countRows($select)) continue;

            for ($i = 1; $i <= $totalColumns; $i++) {
                $id = $model->createRow(array(
                    'component_id' => $c->dbId,
                    'pos' => $i,
                    'visible' => true
                ))->save();

                $s = $c->dbId . '-' . $i;
                $search[$j] = $s;
                $replace[$j] = $c->dbId . '-' . $id;

                $dbPattern[$j][] = $s . '-%';
                $dbPattern[$j][] = $s . '\_%';
                $dbPattern[$j][] = $s;

                $j++;
            }
        }

        if (empty($search)) return;

        $db = Zend_Registry::get('db');
        foreach ($db->listTables() as $table) {
            if ($table == 'cache_component') continue;
            if ($table == 'cache_component_includes') continue;
            if ($table == 'cache_component_url') continue;
            if ($table == 'cache_users') continue;
            $hasComponentId = false;
            $column = 'component_id';
            foreach ($db->query("SHOW FIELDS FROM $table")->fetchAll() as $field) {
                if ($table == 'kwf_pages') {
                    $column = 'parent_id';
                    $hasComponentId = true;
                } else if ($field['Field'] == 'component_id') {
                    $hasComponentId = true;
                }
            }

            if ($hasComponentId) {
                $where = "WHERE ";
                foreach ($search as $key => $value) {
                    $where .= "$column LIKE '" . implode("' OR $column LIKE '", $dbPattern[$key]) . "' OR ";
                }
                $where = substr($where, 0, strlen($where)-4);
                $sql = "SELECT $column FROM $table $where";
                $ids = $db->fetchCol($sql);
                if (empty($ids)) continue;

                $lastUpdatedId = false;
                foreach ($ids as $id) {
                    if ($lastUpdatedId == $id) continue;
                    $k = 0;
                    foreach ($search as $key => $value) {
                        if (strpos($id, $value) !== false) {
                            $k = $key;
                            break;
                        }
                    }
                    $sql = "UPDATE $table SET $column = " . $db->quote(str_replace($search[$k], $replace[$k], $id)) . "
                        WHERE $column = '$id'";
                    $db->query($sql);
                    $lastUpdatedId = $id;
                }
            }
        }

        $where = "WHERE ";
        foreach ($search as $key => $value) {
            $where .= "content LIKE '%href=\"" . implode("\"%' OR content LIKE '%href=\"", $dbPattern[$key]) . "\"%' OR content LIKE '%href=\n  \"" . implode("\"%' OR content LIKE '%href=\n  \"", $dbPattern[$key]) . "\"%' OR ";
        }
        $where = substr($where, 0, strlen($where)-4);

        $sql = "SELECT component_id, content FROM kwc_basic_text $where";
        $rows = $db->query($sql)->fetchAll();
        foreach ($rows as $row) {
            $k = 0;
            foreach ($search as $key => $value) {
                if (strpos($row['content'], $value) !== false) {
                    $row['content'] = preg_replace('#(href=\s*")([^"]*/)?([^"]*)'.preg_quote($search[$key]).'([^"]*)"#',
                                                   '\1\2\3'.$replace[$key].'\4"',
                                                   $row['content']);
                }
            }
            $sql = "UPDATE kwc_basic_text SET content = " . $db->quote($row['content']) . "
                        WHERE component_id = '".$row['component_id']."'";
            $db->query($sql);
        }
    }
927444
public function update(Entity $entity, $primaryValue)
    {
        if (!$entity->getValidator()->validate()) {
            throw new Exception\ValidatorException($entity->getValidator());
        }

        try {

            if (!$this->query()->updateOne($primaryValue, $entity->getData())->run($this->connection)) {
                throw new Exception\RepositoryException("Entity was not successfully updated!");
            }
        } catch (Exception\QueryException $e) {
            throw new Exception\RepositoryException($e->getMessage());
        }

        $this->_saveAssociated($primaryValue, $entity);
    }
157800
public function updateByPK($pk, $values){
        $pkConditions = $this->buildPKConditions($this->pk, $pk);
        return $this->update($values, $pkConditions[0], $pkConditions[1]);
    }
574194
public function dbgInsertMany(array $rows, array $update=[], array $constraint=[]) {
		$sql = $this->buildInsertSQL($rows, $update, $constraint);
		$params = $this->getParameters();

		return $this->replaceParams($sql, $params);
	}
1112108
final public function update($properties=NULL) {
		
		// hook for tasks to be executed before creation
		$this->beforeUpdate();
		
		$app	= Application::getInstance();
		$class	= get_called_class();
		$binds	= static::getBinds();
		
		// if property list is empty, will include all
		$properties	= (array)$properties;
		if (!count($properties)) {
			$properties = array_keys($class::getBinds());
		}
		
		$logParam = $this->getKeyForEventlog();

		// require table primary key and force its assign
		if ($this->areKeysPopulated()) {

			// set an object with fields to update
			$dbObj = $this->prepareData($properties);

			// force to array
			$key = (array)$this->keyProperties;

			$dbKey = new \stdClass();

			// set the table key with values
			foreach ($key as $k) {
				
				// get object property value
				$dbKey->{$binds[$k]} = $this->$k;
					
			}
				
			$res = (bool)$this->db->updateObject($class::TABLE_NAME, $dbObj, $dbKey);
			
			$app->logEvent('Updated ' . $class . ' object with ' . $logParam);

		// object is not populated
		} else {

			$res = FALSE;
			$app->logError('The ' . $class . ' object with ' . $logParam . ' cannot be updated');

		}
		
		// hook for tasks to be executed after creation
		$this->afterUpdate();
		
		return $res;
		
	}
968652
public static function updateOrNull($data = null)
    {
        static $request;
        if (!$request) {
            $request = Di::getDefault()->getShared('request');
        }

        if (!$request->isPost() && !$request->isPut() && !$request->isPatch()) {
            return null;
        }

        $model = new static;

        $pkName = $model->getPrimaryKey();

        $_request = $request->get();

        $instance = static::get(isset($data[$pkName]) ? $data[$pkName] : $request->getId($pkName));

        if ($data === null || !isset($data[0])) {
            foreach ($model->getSafeFields() as $field) {
                if (isset($_request[$field])) {
                    $instance->$field = $_request[$field];
                }
            }
        }

        if ($data) {
            foreach ($data as $k => $v) {
                if (is_int($k)) {
                    $field = $v;
                    if (!isset($_request[$field])) {
                        throw new MissingFieldException($field);
                    }
                    $instance->$field = $_request[$field];
                } else {
                    $instance->$k = $v;
                }
            }
        }

        return $instance->update();
    }
369568
public void update(Object po) throws Exception {
		SqlParamsPairs sqlAndParams = ModelSqlUtils.getUpdateFromObject(po);
		
		getProxy().update(sqlAndParams.getSql(), sqlAndParams.getParams());
	}
1025763
protected function createBelongsToManyRelationship(
        $primaryKey,
        iterable $foreignKeys,
        string $intTableName,
        string $intPrimaryKeyName,
        string $intForeignKeyName
    ): void {
        assert(is_string($primaryKey) === true || is_int($primaryKey) === true);

        try {
            $this->inTransaction(function () use (
                $intTableName,
                $intPrimaryKeyName,
                $intForeignKeyName,
                $primaryKey,
                $foreignKeys
            ): void {
                $connection = $this->getConnection();
                $query      = $connection->createQueryBuilder();

                $query->insert($intTableName)->values([$intPrimaryKeyName => '?', $intForeignKeyName => '?']);
                $statement = $connection->prepare($query->getSQL());

                foreach ($foreignKeys as $value) {
                    assert(is_string($value) === true || is_int($value) === true);
                    $statement->bindValue(1, $primaryKey);
                    $statement->bindValue(2, $value);
                    $statement->execute();
                }
            });
        } /** @noinspection PhpRedundantCatchClauseInspection */ catch (DBALException $exception) {
            $message = 'Belongs-to-Many relationship creation failed.';
            throw new RepositoryException($message, 0, $exception);
        }
    }
848696
protected function _update($postdata, $primary)
    {
        if (!$postdata)
        {
            self::error('$postdata array is empty');
        }
        $res = false;
        $set = array();
        $db = Fruit_db::get_instance($this->connection);
        $fields = array_merge($this->fields, $this->hidden_fields);
        foreach ($postdata as $key => $val)
        {
            if (isset($fields[$key]) && !isset($this->locked_fields[$key]) && !isset($this->custom_fields[$key]))
            {
                if (isset($this->field_type[$key]))
                {
                    switch ($this->field_type[$key])
                    {
                        case 'password':
                            if (trim($val) == '')
                            {
                                continue 2;
                            }
                            elseif ($this->defaults[$key])
                            {
                                $val = hash($this->defaults[$key], $val);
                            }
                            break;
                        case 'fk_relation': //
                            continue 2;
                            break;
                    }
                }
                /*
                if (is_array($val))
                {
                $set[] = '`' . $fields[$key]['table'] . '`.`' . $fields[$key]['field'] . '` = ' . $db->escape(implode(',', $val), false,
                $this->field_type[$key], $this->field_null[$key], isset($this->bit_field[$key]));
                }
                elseif (isset($this->point_field[$key]) && trim($val))
                {
                $set[] = '`' . $fields[$key]['table'] . '`.`' . $fields[$key]['field'] . '` = Point(' . $db->escape($val, true, 'point',
                $this->field_null[$key], isset($this->bit_field[$key])) . ')';
                }
                else
                $set[] = '`' . $fields[$key]['table'] . '`.`' . $fields[$key]['field'] . '` = ' . ((isset($this->no_quotes[$key]) &&
                isset($this->pass_var['edit'][$key])) ? $db->escape($val, true) : $db->escape(trim($val), false, $this->field_type[$key],
                $this->field_null[$key], isset($this->bit_field[$key])));
                */
                $set[] = '`' . $fields[$key]['table'] . '`.`' . $fields[$key]['field'] . '` = ' . $this->prepare_query_field($val, $key,
                    'edit');
            }
        }
        if (!$set)
        {
            self::error('Nothing to update');
        }
        if (!$this->join)
        {
            if (!$this->demo_mode)
                $res = $db->query("UPDATE `{$this->table}` SET " . implode(",\r\n", $set) . " WHERE `{$this->primary_key}` = " . $db->
                    escape($primary) . " LIMIT 1");
        }
        else
        {
            //$tables = array('`' . $this->table . '`');
            $joins = array();
            foreach ($this->join as $alias => $param)
            {
                //$tables[] = '`' . $alias . '`';
                $joins[] = "INNER JOIN `{$param['join_table']}` AS `{$alias}` 
                    ON `{$param['table']}`.`{$param['field']}` = `{$alias}`.`{$param['join_field']}`";
            }
            if (!$this->demo_mode)
                $res = $db->query("UPDATE `{$this->table}` AS `{$this->table}` " . implode(' ', $joins) . " SET " . implode(",\r\n", $set) .
                    " WHERE `{$this->table}`.`{$this->primary_key}` = " . $db->escape($primary));
        }
        if (isset($postdata[$this->table . '.' . $this->primary_key]) && $res)
            $primary = $postdata[$this->table . '.' . $this->primary_key];
        else
        {
            $postdata[$this->table . '.' . $this->primary_key] = $primary;
        }

        if ($this->fk_relation)
        {
            foreach ($this->fk_relation as $fk)
            {
                $field = $fk['table'] . '.' . $fk['field'];
                if (array_key_exists($fk['alias'], $postdata) && array_key_exists($field, $postdata))
                {
                    $in_val = $db->escape($postdata[$field], false, $this->field_type[$field], $this->field_null[$field], isset($this->
                        bit_field[$field]));
                    $db->query('DELETE FROM `' . $fk['fk_table'] . '` WHERE `' . $fk['in_fk_field'] . '` = ' . $in_val . ' AND ' . $this->
                        _build_rel_ins_where($fk['alias']));
                    $fkids = $this->parse_comma_separated($postdata[$fk['alias']]);
                    if ($fkids)
                    {
                        $ins_vals = array();
                        $ins_keys = array();
                        $ins_add = array();
                        if ($fk['add_data'])
                        {
                            foreach ($fk['add_data'] as $add_key => $add_val)
                            {
                                $ins_keys[] = '`' . $add_key . '`';
                                $ins_add[] = $db->escape($add_val);
                            }
                        }
                        $ins_add[] = /*$db->escape(*/ $in_val /*)*/;
                        $ins_keys[] = '`' . $fk['in_fk_field'] . '`';
                        $ins_keys[] = '`' . $fk['out_fk_field'] . '`';
                        foreach ($fkids as $fkid)
                        {
                            $ins_vals[] = '(' . implode(',', $ins_add) . ',' . $db->escape($fkid) . ')';
                        }
                        $db->query('INSERT INTO `' . $fk['fk_table'] . '` (' . implode(',', $ins_keys) . ') VALUES ' . implode(',', $ins_vals));
                    }
                }
            }
        }

        unset($set, $postdata);
        return $primary;
    }
664172
public function upsert($table, $insertFieldValues, $updateFieldValues = [], $primaryKey = null)
    {
        if (!$primaryKey) {
            $primaryKey = (string)key($insertFieldValues);
        }

        if (!$updateFieldValues) {
            $updateFieldValues = $insertFieldValues;
        }

        $fields = array_keys($insertFieldValues);

        $bind = $insertFieldValues;
        $updates = [];
        foreach ($updateFieldValues as $k => $v) {
            $field = is_string($k) ? $k : $v;
            if ($primaryKey === $field) {
                continue;
            }

            if (is_int($k)) {
                $updates[] = "[$field]=:{$field}_dku";
                $bind["{$field}_dku"] = $insertFieldValues[$field];
            } elseif ($v instanceof AssignmentInterface) {
                $v->setFieldName($k);
                $updates[] = $v->getSql();
                /** @noinspection SlowArrayOperationsInLoopInspection */
                $bind = array_merge($bind, $v->getBind());
            } else {
                $updates[] = $v;
            }
        }

        $insertFieldsSql = '[' . implode('],[', $fields) . ']';
        $insertValuesSql = ':' . implode(',:', $fields);

        $updateFieldsSql = implode(',', $updates);

        $sql = 'INSERT' . " INTO {$this->_escapeIdentifier($table)}($insertFieldsSql) VALUES($insertValuesSql) ON DUPLICATE KEY UPDATE $updateFieldsSql";

        return $this->execute('insert', $sql, $bind);
    }
291619
public int update(Entity entity) throws SQLException {
		if (CollectionUtil.isEmpty(entity)) {
			return 0;
		}
		entity = fixEntity(entity);
		Object pk = entity.get(primaryKeyField);
		if (null == pk) {
			throw new SQLException(StrUtil.format("Please determine `{}` for update", primaryKeyField));
		}

		final Entity where = Entity.create(tableName).set(primaryKeyField, pk);
		final Entity record = (Entity) entity.clone();
		record.remove(primaryKeyField);

		return db.update(record, where);
	}
40642
public function delete_many($primary_values)
    {
        $primary_values = $this->trigger('before_delete', $primary_values);

        $this->_database->where_in($this->primary_key, $primary_values);

        if ($this->soft_delete)
        {
            $result = $this->_database->update($this->_table, array( $this->soft_delete_key => TRUE ));
        }
        else
        {
            $result = $this->_database->delete($this->_table);
        }

        $this->trigger('after_delete', $result);

        return $result;
    }