Include scope.TableName() in ORDER statement for First() & Last()

This commit is contained in:
Xavier Dumesnil 2014-04-10 16:29:09 +02:00
parent 1a5a4b707d
commit 5e62e7fdad
2 changed files with 14 additions and 2 deletions

View File

@ -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
}

View File

@ -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)