Skip to content

Commit

Permalink
Allowing multi primary key in BelongsTo
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Jan 7, 2014
1 parent aa43d10 commit 1dc56e9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
4 changes: 2 additions & 2 deletions Cake/ORM/Association.php
Expand Up @@ -93,7 +93,7 @@ abstract class Association {
/**
* The name of the field representing the foreign key to the target table
*
* @var string
* @var string|array
*/
protected $_foreignKey;

Expand Down Expand Up @@ -266,7 +266,7 @@ public function conditions($conditions = null) {
* If no parameters are passed current field is returned
*
* @param string $key the key to be used to link both tables together
* @return string
* @return string|array
*/
public function foreignKey($key = null) {
if ($key !== null) {
Expand Down
29 changes: 18 additions & 11 deletions Cake/ORM/Association/BelongsTo.php
Expand Up @@ -139,17 +139,24 @@ public function save(Entity $entity, $options = []) {
* @return array
*/
protected function _joinCondition(array $options) {
$field = sprintf(
'%s.%s',
$this->target()->alias(),
$this->_targetTable->primaryKey()
);
$value = new IdentifierExpression(sprintf(
'%s.%s',
$this->_sourceTable->alias(),
$options['foreignKey']
));
return [$field => $value];
$conditions = [];
$tAlias = $this->target()->alias();
$sAlias = $this->_sourceTable->alias();
$foreignKey = (array)$options['foreignKey'];
$primaryKey = $this->_targetTable->primaryKey();

if (count($foreignKey) !== count($primaryKey)) {
$msg = 'Cannot match provided foreignKey, got %d columns expected %d';
throw new \RuntimeException(sprintf($msg, count($foreignKey), count($primaryKey)));
}

foreach ($foreignKey as $k => $f) {
$field = sprintf('%s.%s', $tAlias, $primaryKey[$k]);
$value = new IdentifierExpression(sprintf('%s.%s', $sAlias, $f));
$conditions[$field] = $value;
}

return $conditions;
}

}

0 comments on commit 1dc56e9

Please sign in to comment.