Browse Source

Merge pull request #5052 from cakephp/3.0-marshaller-fix

Prefixing primary key with table alias to avoid SQL errors
Mark Story 11 years ago
parent
commit
fd9e4d0a28
2 changed files with 39 additions and 0 deletions
  1. 3 0
      src/ORM/Marshaller.php
  2. 36 0
      tests/TestCase/ORM/MarshallerTest.php

+ 3 - 0
src/ORM/Marshaller.php

@@ -237,6 +237,9 @@ class Marshaller {
 		$target = $assoc->target();
 		$primaryKey = (array)$target->primaryKey();
 		$multi = count($primaryKey) > 1;
+		$primaryKey = array_map(function ($key) use ($target) {
+			return $target->alias() . '.' . $key;
+		}, $primaryKey);
 
 		if ($multi) {
 			if (count(current($ids)) !== count($primaryKey)) {

+ 36 - 0
tests/TestCase/ORM/MarshallerTest.php

@@ -14,6 +14,7 @@
  */
 namespace Cake\Test\TestCase\ORM;
 
+use Cake\Database\Expression\IdentifierExpression;
 use Cake\I18n\Time;
 use Cake\ORM\Entity;
 use Cake\ORM\Marshaller;
@@ -852,6 +853,41 @@ class MarshallerTest extends TestCase {
 
 /**
  * Tests that merging data to an entity containing belongsToMany and _ids
+ * will not generate conflicting queries when associations are automatically selected
+ *
+ * @return void
+ */
+	public function testMergeFromIdsWithAutoAssociation() {
+		$entity = new Entity([
+			'title' => 'Haz tags',
+			'body' => 'Some content here',
+			'tags' => [
+				new Entity(['id' => 1, 'name' => 'Cake']),
+				new Entity(['id' => 2, 'name' => 'PHP'])
+			]
+		]);
+
+		$data = [
+			'title' => 'Haz moar tags',
+			'tags' => ['_ids' => [1, 2, 3]]
+		];
+		$entity->accessible('*', true);
+
+		// Adding a forced join to have another table with the same column names
+		$this->articles->Tags->eventManager()->attach(function ($e, $query) {
+			$left = new IdentifierExpression('Tags.id');
+			$right = new IdentifierExpression('a.id');
+			$query->leftJoin(['a' => 'tags'], $query->newExpr()->eq($left, $right));
+		}, 'Model.beforeFind');
+
+		$marshall = new Marshaller($this->articles);
+		$result = $marshall->merge($entity, $data, ['associated' => ['Tags']]);
+
+		$this->assertCount(3, $result->tags);
+	}
+
+/**
+ * Tests that merging data to an entity containing belongsToMany and _ids
  * will ignore empty values.
  *
  * @return void