Browse Source

Fix entity saving when '' is used as a primary key value.

Having '' as the primary key value is almost never wanted as '' is cast
to null or 0. Instead filter out this value and treat it as a mistake.

Refs #4152
mark_story 11 years ago
parent
commit
90a7016e93
2 changed files with 27 additions and 4 deletions
  1. 7 4
      src/ORM/Table.php
  2. 20 0
      tests/TestCase/ORM/TableTest.php

+ 7 - 4
src/ORM/Table.php

@@ -1150,11 +1150,14 @@ class Table implements RepositoryInterface, EventListener {
 
 		if ($primary && $entity->isNew()) {
 			$alias = $this->alias();
-			$keys = array_keys($primary);
-			foreach ($keys as &$pk) {
-				$pk = "$alias.$pk";
+			$conditions = [];
+			foreach ($primary as $k => $v) {
+				if ($v === '') {
+					$entity->unsetProperty($k);
+				}
+				$conditions["$alias.$k"] = $v;
 			}
-			$entity->isNew(!$this->exists(array_combine($keys, $primary)));
+			$entity->isNew(!$this->exists($conditions));
 		}
 
 		$associated = $options['associated'];

+ 20 - 0
tests/TestCase/ORM/TableTest.php

@@ -1213,6 +1213,26 @@ class TableTest extends \Cake\TestSuite\TestCase {
 	}
 
 /**
+ * Test that saving a new entity with an empty id populates
+ * the entity's id field.
+ *
+ * @group save
+ * @return void
+ */
+	public function testSaveNewEntityEmptyIdField() {
+		$entity = new \Cake\ORM\Entity([
+			'id' => '',
+			'username' => 'superuser',
+			'password' => 'root',
+			'created' => new Time('2013-10-10 00:00'),
+			'updated' => new Time('2013-10-10 00:00')
+		]);
+		$table = TableRegistry::get('users');
+		$this->assertSame($entity, $table->save($entity));
+		$this->assertEquals($entity->id, self::$nextUserId);
+	}
+
+/**
  * Tests that saving an entity will filter out properties that
  * are not present in the table schema when saving
  *