Browse Source

Merge pull request #4264 from cakephp/3.0-fix-reciprocal-btm

Fixes #4253
Mark Story 11 years ago
parent
commit
5745e00b71
2 changed files with 33 additions and 5 deletions
  1. 9 5
      src/ORM/Association/BelongsToMany.php
  2. 24 0
      tests/TestCase/ORM/QueryRegressionTest.php

+ 9 - 5
src/ORM/Association/BelongsToMany.php

@@ -181,16 +181,20 @@ class BelongsToMany extends Association {
 		}
 
 		if (!$target->association($junctionAlias)) {
+			$target->hasMany($junctionAlias, [
+				'targetTable' => $table,
+				'foreignKey' => $this->targetForeignKey(),
+			]);
+		}
+
+		if (!$target->association($sAlias)) {
 			$target->belongsToMany($sAlias, [
-				'sourceTable' => $source,
+				'sourceTable' => $target,
+				'targetTable' => $source,
 				'foreignKey' => $this->targetForeignKey(),
 				'targetForeignKey' => $this->foreignKey(),
 				'through' => $table
 			]);
-			$target->hasMany($junctionAlias, [
-				'targetTable' => $table,
-				'foreignKey' => $this->targetForeignKey(),
-			]);
 		}
 
 		if (!$source->association($table->alias())) {

+ 24 - 0
tests/TestCase/ORM/QueryRegressionTest.php

@@ -178,6 +178,30 @@ class QueryRegressionTest extends TestCase {
 	}
 
 /**
+ * Test for https://github.com/cakephp/cakephp/issues/4253
+ *
+ * Makes sure that the belongsToMany association is not overwritten with conflicting information
+ * by any of the sides when the junction() function is invoked
+ *
+ * @return void
+ */
+	public function testReciprocalBelongsToMany2() {
+		$articles = TableRegistry::get('Articles');
+		$tags = TableRegistry::get('Tags');
+
+		$articles->belongsToMany('Tags');
+		$tags->belongsToMany('Articles');
+
+		$result = $articles->find()->contain(['Tags'])->first();
+		$sub = $articles->Tags->find()->select(['id'])->matching('Articles', function($q) use ($result) {
+			return $q->where(['Articles.id' => 1]);
+		});
+
+		$query = $articles->Tags->find()->where(['id NOT IN' => $sub]);
+		$this->assertEquals(1, $query->count());
+	}
+
+/**
  * Returns an array with the saving strategies for a belongsTo association
  *
  * @return array