Skip to content
Permalink
Browse files

Fixing bindingKey for HasOne and adding test for it

  • Loading branch information...
lorenzo committed Jul 2, 2015
1 parent 7ca6baf commit 5739a30ce9327fdcbb4bd1608bdb0570db078699
Showing with 43 additions and 7 deletions.
  1. +4 −4 src/ORM/Association.php
  2. +39 −3 tests/TestCase/ORM/BindingKeyTest.php
@@ -781,20 +781,20 @@ protected function _joinCondition($options)
$tAlias = $this->target()->alias();
$sAlias = $this->source()->alias();
$foreignKey = (array)$options['foreignKey'];
$primaryKey = (array)$this->_sourceTable->primaryKey();
$bindingKey = (array)$this->bindingKey();
if (count($foreignKey) !== count($primaryKey)) {
if (count($foreignKey) !== count($bindingKey)) {
$msg = 'Cannot match provided foreignKey for "%s", got "(%s)" but expected foreign key for "(%s)"';
throw new RuntimeException(sprintf(
$msg,
$this->_name,
implode(', ', $foreignKey),
implode(', ', $primaryKey)
implode(', ', $bindingKey)
));
}
foreach ($foreignKey as $k => $f) {
$field = sprintf('%s.%s', $sAlias, $primaryKey[$k]);
$field = sprintf('%s.%s', $sAlias, $bindingKey[$k]);
$value = new IdentifierExpression(sprintf('%s.%s', $tAlias, $f));
$conditions[$field] = $value;
}
@@ -30,20 +30,33 @@ class BindingKeyTest extends TestCase
*/
public $fixtures = [
'core.users',
'core.auth_users'
'core.auth_users',
'core.site_authors'
];
/**
* Data provider for the two types of strategies BelongsTo and HasOne implements
*
* @return void
*/
public function strategiesProviderJoinable()
{
return [['join'], ['select']];
}
/**
* Tests that bindingKey can be used in belongsTo associations
*
* @dataProvider strategiesProviderJoinable
* @return void
*/
public function testBelongsto()
public function testBelongsto($strategy)
{
$users = TableRegistry::get('Users');
$users->belongsTo('AuthUsers', [
'bindingKey' => 'username',
'foreignKey' => 'username'
'foreignKey' => 'username',
'strategy' => $strategy
]);
$result = $users->find()
@@ -62,4 +75,27 @@ public function testBelongsto()
$result->combine('id', 'auth_user.id')->toArray()
);
}
/**
* Tests that bindingKey can be used in hasOne associations
*
* @dataProvider strategiesProviderJoinable
* @return void
*/
public function testHasOne($strategy) {
$users = TableRegistry::get('Users');
$users->hasOne('SiteAuthors', [
'bindingKey' => 'username',
'foreignKey' => 'name',
'strategy' => $strategy
]);
$users->updateAll(['username' => 'jose'], ['username' => 'garrett']);
$result = $users->find()
->contain(['SiteAuthors'])
->where(['username' => 'jose'])
->first();
$this->assertEquals(3, $result->site_author->id);
}
}

0 comments on commit 5739a30

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