Skip to content

Commit

Permalink
Merge pull request #30 from robertpustulka/fix-associations
Browse files Browse the repository at this point in the history
Fix association type for field versions.
  • Loading branch information
josegonzalez authored Apr 20, 2017
2 parents b757edc + 4257798 commit 1a30771
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 13 deletions.
30 changes: 17 additions & 13 deletions src/Model/Behavior/VersionBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,27 +117,31 @@ public function versionAssociation($field = null, $options = [])
if (!$this->_table->associations()->has($name)) {
$model = $this->_config['referenceName'];

$options += [
'className' => $this->_config['versionTable'],
'foreignKey' => $this->_config['foreignKey'],
'strategy' => 'subquery',
'dependent' => true
];

if ($field) {
$this->_table->hasOne($name, $options + [
'className' => $this->_config['versionTable'],
'foreignKey' => $this->_config['foreignKey'],
'joinType' => 'LEFT',
$options += [
'conditions' => [
$name . '.model' => $model,
$name . '.field' => $field,
],
'propertyName' => $field . '_version'
]);
];
} else {
$this->_table->hasMany($name, $options + [
'className' => $this->_config['versionTable'],
'foreignKey' => $this->_config['foreignKey'],
'strategy' => 'subquery',
'conditions' => ["$name.model" => $model],
'propertyName' => '__version',
'dependent' => true
]);
$options += [
'conditions' => [
$name . '.model' => $model
],
'propertyName' => '__version'
];
}

$this->_table->hasMany($name, $options);
}

return $this->_table->association($name);
Expand Down
21 changes: 21 additions & 0 deletions tests/TestCase/Model/Behavior/VersionBehaviorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -348,4 +348,25 @@ public function testGetAdditionalMetaData()
$this->assertSame(2, $results[0]['_versions'][1]['version_user_id']);
$this->assertSame(3, $results[0]['_versions'][2]['version_user_id']);
}

/**
* @return void
*/
public function testAssociations()
{
$table = TableRegistry::get('Articles', [
'entityClass' => 'Josegonzalez\Version\Test\TestCase\Model\Behavior\TestEntity'
]);
$table->addBehavior('Josegonzalez/Version.Version');

$this->assertTrue($table->associations()->has('articleversion'));
$versions = $table->association('articleversion');
$this->assertInstanceOf('Cake\Orm\Association\HasMany', $versions);
$this->assertEquals('__version', $versions->property());

$this->assertTrue($table->associations()->has('articlebodyversion'));
$bodyVersions = $table->association('articlebodyversion');
$this->assertInstanceOf('Cake\Orm\Association\HasMany', $bodyVersions);
$this->assertEquals('body_version', $bodyVersions->property());
}
}

0 comments on commit 1a30771

Please sign in to comment.