Browse Source

Fix custom keys in belongsToMany

Use custom keys correctly in the generated associations on the junction
table for belongsToMany associations.

Refs #7600
Mark Story 10 years ago
parent
commit
cbdfd0a5c4

+ 7 - 4
src/ORM/Association/BelongsToMany.php

@@ -210,6 +210,13 @@ class BelongsToMany extends Association
             ]);
         }
 
+        if (!$source->association($junctionAlias)) {
+            $source->hasMany($junctionAlias, [
+                'targetTable' => $table,
+                'foreignKey' => $this->foreignKey(),
+            ]);
+        }
+
         if (!$target->association($sAlias)) {
             $target->belongsToMany($sAlias, [
                 'sourceTable' => $target,
@@ -220,10 +227,6 @@ class BelongsToMany extends Association
             ]);
         }
 
-        if (!$source->association($table->alias())) {
-            $source->hasMany($junctionAlias)->target($table);
-        }
-
         return $this->_junctionTable = $table;
     }
 

+ 26 - 0
tests/TestCase/ORM/Association/BelongsToManyTest.php

@@ -193,6 +193,32 @@ class BelongsToManyTest extends TestCase
     }
 
     /**
+     * Tests the junction method custom keys
+     *
+     * @return void
+     */
+    public function testJunctionCustomKeys()
+    {
+        $this->article->belongsToMany('Tags', [
+            'joinTable' => 'articles_tags',
+            'foreignKey' => 'article',
+            'targetForeignKey' => 'tag'
+        ]);
+        $this->tag->belongsToMany('Articles', [
+            'joinTable' => 'articles_tags',
+            'foreignKey' => 'tag',
+            'targetForeignKey' => 'article'
+        ]);
+        $junction = $this->article->association('Tags')->junction();
+        $this->assertEquals('article', $junction->association('Articles')->foreignKey());
+        $this->assertEquals('article', $this->article->association('ArticlesTags')->foreignKey());
+
+        $junction = $this->tag->association('Articles')->junction();
+        $this->assertEquals('tag', $junction->association('Tags')->foreignKey());
+        $this->assertEquals('tag', $this->tag->association('ArticlesTags')->foreignKey());
+    }
+
+    /**
      * Tests it is possible to set the table name for the join table
      *
      * @return void

+ 1 - 1
tests/TestCase/ORM/QueryRegressionTest.php

@@ -213,7 +213,7 @@ class QueryRegressionTest extends TestCase
      *
      * @return void
      */
-    public function testReciprocalBelongsToMany2()
+    public function testReciprocalBelongsToManyNoOverwrite()
     {
         $articles = TableRegistry::get('Articles');
         $tags = TableRegistry::get('Tags');