Permalink
Browse files

Allowing multi primary key in BelongsTo

  • Loading branch information...
1 parent aa43d10 commit 1dc56e9167f727b5cb5a04748887654beaf4a7ad @lorenzo lorenzo committed Jan 7, 2014
Showing with 20 additions and 13 deletions.
  1. +2 −2 Cake/ORM/Association.php
  2. +18 −11 Cake/ORM/Association/BelongsTo.php
View
@@ -93,7 +93,7 @@
/**
* The name of the field representing the foreign key to the target table
*
- * @var string
+ * @var string|array
*/
protected $_foreignKey;
@@ -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) {
@@ -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.