From 5e62e7fdad2a56ccd57f67bc4831b3816c8d1779 Mon Sep 17 00:00:00 2001 From: Xavier Dumesnil Date: Thu, 10 Apr 2014 16:29:09 +0200 Subject: [PATCH] Include scope.TableName() in ORDER statement for First() & Last() --- main.go | 4 ++-- main_test.go | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 942880b5..c98ca2b6 100644 --- a/main.go +++ b/main.go @@ -131,13 +131,13 @@ func (s *DB) Assign(attrs ...interface{}) *DB { func (s *DB) First(out interface{}, where ...interface{}) *DB { scope := s.clone().NewScope(out) - scope.Search = scope.Search.clone().order(scope.PrimaryKey()).limit(1) + scope.Search = scope.Search.clone().order(scope.TableName()+"."+scope.PrimaryKey()).limit(1) return scope.inlineCondition(where...).callCallbacks(s.parent.callback.queries).db } func (s *DB) Last(out interface{}, where ...interface{}) *DB { scope := s.clone().NewScope(out) - scope.Search = scope.Search.clone().order(scope.PrimaryKey() + " DESC").limit(1) + scope.Search = scope.Search.clone().order(scope.TableName()+"."+scope.PrimaryKey() + " DESC").limit(1) return scope.inlineCondition(where...).callCallbacks(s.parent.callback.queries).db } diff --git a/main_test.go b/main_test.go index 2434c8ef..31771a2c 100644 --- a/main_test.go +++ b/main_test.go @@ -247,6 +247,18 @@ func TestFirstAndLast(t *testing.T) { } } +func TestFirstAndLastWithJoins(t *testing.T) { + var user1, user2, user3, user4 User + db.Joins("left join emails on emails.user_id = users.id").First(&user1) + db.Order("id").Find(&user2) + + db.Joins("left join emails on emails.user_id = users.id").Last(&user3) + db.Order("id desc").Find(&user4) + if user1.Id != user2.Id || user3.Id != user4.Id { + t.Errorf("First and Last should works correctly") + } +} + func TestFirstAndLastForTableWithNoStdPrimaryKey(t *testing.T) { var animal1, animal2, animal3, animal4 Animal db.First(&animal1)