From b0445f72e4cce324308bb32384d578e43753cd6d Mon Sep 17 00:00:00 2001 From: Jonathon Menz Date: Tue, 18 Oct 2016 20:49:47 -0700 Subject: [PATCH] FIX Ambiguous column SQL error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Specify the table for the field we’re fetching, in case a joined table has a field with the same name --- model/DataQuery.php | 12 ++++++++---- tests/model/DataListTest.php | 11 +++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/model/DataQuery.php b/model/DataQuery.php index fe7cb7d62..cf8fe839b 100644 --- a/model/DataQuery.php +++ b/model/DataQuery.php @@ -392,7 +392,8 @@ class DataQuery { * automatically so must not contain double quotes. */ public function max($field) { - return $this->aggregate("MAX(\"$field\")"); + $table = ClassInfo::table_for_object_field($this->dataClass, $field); + return $this->aggregate("MAX(\"$table\".\"$field\")"); } /** @@ -402,7 +403,8 @@ class DataQuery { * automatically so must not contain double quotes. */ public function min($field) { - return $this->aggregate("MIN(\"$field\")"); + $table = ClassInfo::table_for_object_field($this->dataClass, $field); + return $this->aggregate("MIN(\"$table\".\"$field\")"); } /** @@ -412,7 +414,8 @@ class DataQuery { * automatically so must not contain double quotes. */ public function avg($field) { - return $this->aggregate("AVG(\"$field\")"); + $table = ClassInfo::table_for_object_field($this->dataClass, $field); + return $this->aggregate("AVG(\"$table\".\"$field\")"); } /** @@ -422,7 +425,8 @@ class DataQuery { * automatically so must not contain double quotes. */ public function sum($field) { - return $this->aggregate("SUM(\"$field\")"); + $table = ClassInfo::table_for_object_field($this->dataClass, $field); + return $this->aggregate("SUM(\"$table\".\"$field\")"); } /** diff --git a/tests/model/DataListTest.php b/tests/model/DataListTest.php index 87a695f17..21299c88e 100755 --- a/tests/model/DataListTest.php +++ b/tests/model/DataListTest.php @@ -363,6 +363,17 @@ class DataListTest extends SapphireTest { $this->assertEquals($otherExpected, $otherMap); } + public function testAmbiguousAggregate() { + // Test that we avoid ambiguity error when a field exists on two joined tables + // Fetch the sponsors in a round-about way to simulate this + $teamID = $this->idFromFixture('DataObjectTest_Team','team2'); + $sponsors = DataObjectTest_EquipmentCompany::get()->filter('SponsoredTeams.ID', $teamID); + $this->assertNotNull($sponsors->Max('ID')); + $this->assertNotNull($sponsors->Min('ID')); + $this->assertNotNull($sponsors->Avg('ID')); + $this->assertNotNull($sponsors->Sum('ID')); + } + public function testEach() { $list = DataObjectTest_TeamComment::get();