diff --git a/lib/Cake/Model/Datasource/Database/Query.php b/lib/Cake/Model/Datasource/Database/Query.php index fef536e7db7..b9997cd0cf9 100644 --- a/lib/Cake/Model/Datasource/Database/Query.php +++ b/lib/Cake/Model/Datasource/Database/Query.php @@ -1126,7 +1126,7 @@ public function insert() { public function update($table) { $this->_dirty = true; $this->_type = 'update'; - $this->_parts['update'][] = $table; + $this->_parts['update'][0] = $table; return $this; } @@ -1135,19 +1135,24 @@ public function update($table) { * * @param string|array|QueryExpression $key The column name or array of keys * + values to set. This can also be a QueryExpression containing a SQL fragment. - * @param mixed $value The value to update $key to. Can be null if $key is an - * array or QueryExpression + * @param mixed $value The value to update $key to. Can be null if $key is an + * array or QueryExpression. When $key is an array, this parameter will be + * used as $types instead. + * @param array $types The column types to treat data as. * @return Query */ - public function set($key, $value = null) { + public function set($key, $value = null, $types = []) { if (empty($this->_parts['set'])) { - $this->_parts['set'] = new QueryExpression([], [], ','); + $this->_parts['set'] = $this->newExpr()->type(','); } - $set = $key; - if (!is_array($key) && !($key instanceof QueryExpression)) { - $set = [$key => $value]; + if (is_array($key) || $key instanceof QueryExpression) { + $this->_parts['set']->add($key, (array)$value); + } else { + if (is_string($types)) { + $types = [$key => $types]; + } + $this->_parts['set']->add([$key => $value], $types); } - $this->_parts['set']->add($set, []); return $this; } diff --git a/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php b/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php index 163ae3d7ade..bca04cfb888 100644 --- a/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php +++ b/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php @@ -1659,8 +1659,8 @@ public function testUpdateMultipleFields() { $this->_insertTwoRecords(); $query = new Query($this->connection); $query->update('articles') - ->set('title', 'mark') - ->set('body', 'some text') + ->set('title', 'mark', 'string') + ->set('body', 'some text', 'string') ->where(['id' => 1]); $result = $query->sql(false); @@ -1686,7 +1686,7 @@ public function testUpdateMultipleFieldsArray() { ->set([ 'title' => 'mark', 'body' => 'some text' - ]) + ], ['title' => 'string', 'body' => 'string']) ->where(['id' => 1]); $result = $query->sql(false); @@ -1700,6 +1700,11 @@ public function testUpdateMultipleFieldsArray() { $this->assertCount(1, $result); } +/** + * Test updates with an expression. + * + * @return void + */ public function testUpdateWithExpression() { $this->_insertTwoRecords(); $query = new Query($this->connection);