Browse Source

Prefixing primary key with table alias to avoid SQL errors

Fixes #5044
Jose Lorenzo Rodriguez 11 years ago
parent
commit
7025780a22
2 changed files with 36 additions and 0 deletions
  1. 3 0
      src/ORM/Marshaller.php
  2. 33 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)) {

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

@@ -852,6 +852,39 @@ 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) {
+			$query->leftJoin(['a' => 'tags'], ['Tags.id = a.id']);
+		}, '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