Skip to content
Permalink
Browse files

Implemented targetForeignKey in BelongsToMany, this will be used to

control what keys are used to join
  • Loading branch information...
lorenzo committed Jan 9, 2014
1 parent cf9ee7b commit 6fde3191a4499253a5646a6baab8acee9de19675
@@ -91,7 +91,7 @@ abstract class Association {
protected $_className;
/**
* The name of the field representing the foreign key to the target table
* The name of the field representing the foreign key to the table to load
*
* @var string|array
*/
@@ -107,6 +107,31 @@ class BelongsToMany extends Association {
*/
protected $_saveStrategy = self::SAVE_REPLACE;
/**
* The name of the field representing the foreign key to the target table
*
* @var string|array
*/
protected $_targetForeignKey;
/**
* Sets the name of the field representing the foreign key to the target table.
* If no parameters are passed current field is returned
*
* @param string $key the key to be used to link both tables together
* @return string
*/
public function targetForeignKey($key = null) {
if ($key === null) {
if ($this->_targetForeignKey === null) {
$key = Inflector::singularize($this->target()->alias());
$this->_targetForeignKey = Inflector::underscore($key) . '_id';
}
return $this->_targetForeignKey;
}
return $this->_targetForeignKey = $key;
}
/**
* Sets the table instance for the junction relation. If no arguments
* are passed, the current configured table instance is returned
@@ -901,6 +926,9 @@ protected function _options(array $opts) {
if (!empty($opts['saveStrategy'])) {
$this->saveStrategy($opts['saveStrategy']);
}
if (!empty($opts['targetForeignKey'])) {
$this->targetForeignKey($opts['targetForeignKey']);
}
$this->_externalOptions($opts);
}
@@ -45,7 +45,7 @@ public function canBeJoined($options = []) {
}
/**
* Sets the name of the field representing the foreign key to the target table.
* Sets the name of the field representing the foreign key to the source table.
* If no parameters are passed current field is returned
*
* @param string $key the key to be used to link both tables together
@@ -1294,4 +1294,26 @@ public function testSaveOnlyEntities() {
$association->save($entity);
}
/**
* Tests that targetForeignKey() returns the correct configured value
*
* @return void
*/
public function testTargetForeignKey() {
$assoc = new BelongsToMany('Test', [
'sourceTable' => $this->article,
'targetTable' => $this->tag
]);
$this->assertEquals('tag_id', $assoc->targetForeignKey());
$assoc->targetForeignKey('another_key');
$this->assertEquals('another_key', $assoc->targetForeignKey());
$assoc = new BelongsToMany('Test', [
'sourceTable' => $this->article,
'targetTable' => $this->tag,
'targetForeignKey' => 'foo'
]);
$this->assertEquals('foo', $assoc->targetForeignKey());
}
}

0 comments on commit 6fde319

Please sign in to comment.
You can’t perform that action at this time.