mirror of https://github.com/go-gorm/gorm.git
Include scope.TableName() in ORDER statement for First() & Last()
This commit is contained in:
parent
1a5a4b707d
commit
5e62e7fdad
4
main.go
4
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
|
||||
}
|
||||
|
||||
|
|
12
main_test.go
12
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)
|
||||
|
|
Loading…
Reference in New Issue