Merge pull request #3956 from kinglozzer/pulls/3954-dataquery-relations

FIX: DataQuery::applyRelation using incorrect foreign key (fixes #3954)
This commit is contained in:
Daniel Hensby 2015-03-03 00:13:02 +00:00
commit f7fe045627
2 changed files with 17 additions and 3 deletions

View File

@ -608,8 +608,7 @@ class DataQuery {
$model = singleton($modelClass); $model = singleton($modelClass);
if ($component = $model->has_one($rel)) { if ($component = $model->has_one($rel)) {
if(!$this->query->isJoinedTo($component)) { if(!$this->query->isJoinedTo($component)) {
$has_one = array_flip($model->has_one()); $foreignKey = $rel;
$foreignKey = $has_one[$component];
$realModelClass = ClassInfo::table_for_object_field($modelClass, "{$foreignKey}ID"); $realModelClass = ClassInfo::table_for_object_field($modelClass, "{$foreignKey}ID");
$this->query->addLeftJoin($component, $this->query->addLeftJoin($component,
"\"$component\".\"ID\" = \"{$realModelClass}\".\"{$foreignKey}ID\""); "\"$component\".\"ID\" = \"{$realModelClass}\".\"{$foreignKey}ID\"");

View File

@ -49,6 +49,19 @@ class DataQueryTest extends SapphireTest {
$dq->sql()); $dq->sql());
} }
public function testApplyRelation() {
// Test applyRelation with two has_ones pointing to the same class
$dq = new DataQuery('DataQueryTest_B');
$dq->applyRelation('TestC');
$this->assertTrue($dq->query()->isJoinedTo('DataQueryTest_C'));
$this->assertContains('"DataQueryTest_C"."ID" = "DataQueryTest_B"."TestCID"', $dq->sql());
$dq = new DataQuery('DataQueryTest_B');
$dq->applyRelation('TestCTwo');
$this->assertTrue($dq->query()->isJoinedTo('DataQueryTest_C'));
$this->assertContains('"DataQueryTest_C"."ID" = "DataQueryTest_B"."TestCTwoID"', $dq->sql());
}
public function testApplyReplationDeepInheretence() { public function testApplyReplationDeepInheretence() {
$newDQ = new DataQuery('DataQueryTest_E'); $newDQ = new DataQuery('DataQueryTest_E');
//apply a relation to a relation from an ancestor class //apply a relation to a relation from an ancestor class
@ -253,6 +266,7 @@ class DataQueryTest_B extends DataObject implements TestOnly {
private static $has_one = array( private static $has_one = array(
'TestC' => 'DataQueryTest_C', 'TestC' => 'DataQueryTest_C',
'TestCTwo' => 'DataQueryTest_C',
); );
} }
@ -269,7 +283,8 @@ class DataQueryTest_C extends DataObject implements TestOnly {
private static $has_many = array( private static $has_many = array(
'TestAs' => 'DataQueryTest_A', 'TestAs' => 'DataQueryTest_A',
'TestBs' => 'DataQueryTest_B', 'TestBs' => 'DataQueryTest_B.TestC',
'TestBsTwo' => 'DataQueryTest_B.TestCTwo',
); );
private static $many_many = array( private static $many_many = array(