Browse Source

Fixed Query::set() to apply field types when an array is passed, closes #2836

Jose Lorenzo Rodriguez 12 years ago
parent
commit
faf67c824b
2 changed files with 40 additions and 7 deletions
  1. 11 7
      src/Database/Query.php
  2. 29 0
      tests/TestCase/Database/QueryTest.php

+ 11 - 7
src/Database/Query.php

@@ -1424,14 +1424,18 @@ class Query implements ExpressionInterface, IteratorAggregate {
 		if (empty($this->_parts['set'])) {
 			$this->_parts['set'] = $this->newExpr()->type(',');
 		}
-		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->defaultTypes());
+
+		if (is_array($key) || $key instanceof ExpressionInterface) {
+			$types = (array)$value;
+			$this->_parts['set']->add($key, $types + $this->defaultTypes());
+			return $this;
 		}
+
+		if (is_string($types) && is_string($key)) {
+			$types = [$key => $types];
+		}
+		$this->_parts['set']->eq($key, $value, $types + $this->defaultTypes());
+
 		return $this;
 	}
 

+ 29 - 0
tests/TestCase/Database/QueryTest.php

@@ -1818,6 +1818,35 @@ class QueryTest extends TestCase {
 	}
 
 /**
+ * Test update with array fields and types.
+ *
+ * @return void
+ */
+	public function testUpdateArrayFields() {
+		$query = new Query($this->connection);
+		$date = new \DateTime;
+		$query->update('comments')
+			->set(['comment' => 'mark', 'created' => $date], ['created' => 'date'])
+			->where(['id' => 1]);
+		$result = $query->sql();
+
+		$this->assertQuotedQuery(
+			'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
+			$result,
+			true
+		);
+
+		$this->assertQuotedQuery(' WHERE <id> = :c2$', $result, true);
+		$result = $query->execute();
+		$this->assertCount(1, $result);
+
+		$query = new Query($this->connection);
+		$result = $query->select('created')->from('comments')->where(['id' => 1])->execute();
+		$result = $result->fetchAll('assoc')[0]['created'];
+		$this->assertEquals($date->format('Y-m-d'), $result);
+	}
+
+/**
  * You cannot call values() before insert() it causes all sorts of pain.
  *
  * @expectedException Cake\Error\Exception