Permalink
Browse files

Do not eagerly set the junction relation.

This avoids some recursion problems when using the 'through' config when
setting belongsToMany associations.
  • Loading branch information...
1 parent a65934b commit 3eecc76913f908f78b4381f871644b4fae079e30 @bar bar committed Mar 2, 2014
Showing with 22 additions and 9 deletions.
  1. +20 −9 src/ORM/Association/BelongsToMany.php
  2. +2 −0 tests/TestCase/ORM/Association/BelongsToManyTest.php
View
29 src/ORM/Association/BelongsToMany.php
@@ -116,6 +116,13 @@ class BelongsToMany extends Association {
protected $_targetForeignKey;
/**
+ * The table instance for the junction relation.
+ *
+ * @var string|\Cake\ORM\Table $table Name or instance for the join table
+ */
+ protected $_through;
+
+/**
* Sets the name of the field representing the foreign key to the target table.
* If no parameters are passed current field is returned
*
@@ -148,14 +155,18 @@ public function junction($table = null) {
if ($table === null) {
if (empty($this->_junctionTable)) {
- $tableName = $this->_junctionTableName();
- $tableAlias = Inflector::camelize($tableName);
-
- $config = [];
- if (!TableRegistry::exists($tableAlias)) {
- $config = ['table' => $tableName];
+ if (!empty($this->_through)) {
+ $table = $this->_through;
+ } else {
+ $tableName = $this->_junctionTableName();
+ $tableAlias = Inflector::camelize($tableName);
+
+ $config = [];
+ if (!TableRegistry::exists($tableAlias)) {
+ $config = ['table' => $tableName];
+ }
+ $table = TableRegistry::get($tableAlias, $config);
}
- $table = TableRegistry::get($tableAlias, $config);
} else {
return $this->_junctionTable;
}
@@ -944,8 +955,8 @@ protected function _junctionTableName($name = null) {
/**
* Parse extra options passed in the constructor.
- * @param array $opts original list of options passed in constructor
*
+ * @param array $opts original list of options passed in constructor
* @return void
*/
protected function _options(array $opts) {
@@ -957,7 +968,7 @@ protected function _options(array $opts) {
$this->_junctionTableName($opts['joinTable']);
}
if (!empty($opts['through'])) {
- $this->junction($opts['through']);
+ $this->_through = $opts['through'];
}
if (!empty($opts['saveStrategy'])) {
$this->saveStrategy($opts['saveStrategy']);
View
2 tests/TestCase/ORM/Association/BelongsToManyTest.php
@@ -1085,6 +1085,7 @@ public function testUnlinkSuccess() {
'joinTable' => 'tags_articles'
];
$assoc = $this->article->belongsToMany('Test', $config);
+ $assoc->junction();
$this->article->association('ArticlesTags')
->conditions(['foo' => 1]);
@@ -1248,6 +1249,7 @@ public function testReplaceLinkSuccess() {
['_collectJointEntities', '_saveTarget'],
['tags', $config]
);
+ $assoc->junction();
$this->article
->association('ArticlesTags')

0 comments on commit 3eecc76

Please sign in to comment.