yii\db\QueryBuilder::update PHP Method

update() public method

For example, php $params = []; $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params); The method will properly escape the table and column names.
public update ( string $table, array $columns, array | string $condition, array &$params ) : string
$table string the table to be updated.
$columns array the column data (name => value) to be updated.
$condition array | string the condition that will be put in the WHERE part. Please refer to [[Query::where()]] on how to specify condition.
$params array the binding parameters that will be modified by this method so that they can be bound to the DB command later.
return string the UPDATE SQL
    public function update($table, $columns, $condition, &$params)
    {
        if (($tableSchema = $this->db->getTableSchema($table)) !== null) {
            $columnSchemas = $tableSchema->columns;
        } else {
            $columnSchemas = [];
        }
        $lines = [];
        foreach ($columns as $name => $value) {
            if ($value instanceof Expression) {
                $lines[] = $this->db->quoteColumnName($name) . '=' . $value->expression;
                foreach ($value->params as $n => $v) {
                    $params[$n] = $v;
                }
            } else {
                $phName = self::PARAM_PREFIX . count($params);
                $lines[] = $this->db->quoteColumnName($name) . '=' . $phName;
                $params[$phName] = !is_array($value) && isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
            }
        }
        $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
        $where = $this->buildWhere($condition, $params);
        return $where === '' ? $sql : $sql . ' ' . $where;
    }

Usage Example

Exemplo n.º 1
0
 /**
  * @inheritdoc
  */
 public function update($table, $columns, $condition, &$params)
 {
     $schema = $this->db->getSchema();
     if (($tableSchema = $schema->getTableSchema($table)) !== null) {
         $columnSchemas = $tableSchema->columns;
     } else {
         $columnSchemas = [];
     }
     foreach ($columns as $name => $value) {
         if ($value instanceof Expression) {
             $columns[$name] = $this->convertExpression($value);
         } elseif (isset($columnSchemas[$name]) && in_array($columnSchemas[$name]->type, [Schema::TYPE_TEXT, Schema::TYPE_BINARY])) {
             $columns[$name] = [$value, \PDO::PARAM_LOB];
         }
     }
     return parent::update($table, $columns, $condition, $params);
 }
All Usage Examples Of yii\db\QueryBuilder::update