diff --git a/query_test.go b/query_test.go index 854beb6d..0aceaf80 100644 --- a/query_test.go +++ b/query_test.go @@ -55,6 +55,24 @@ func TestFirstAndLastWithNoStdPrimaryKey(t *testing.T) { } } +func TestFirstAndLastWithRaw(t *testing.T) { + user1 := User{Name: "user", Emails: []Email{{Email: "user1@example.com"}}} + user2 := User{Name: "user", Emails: []Email{{Email: "user2@example.com"}}} + DB.Save(&user1) + DB.Save(&user2) + + var user3, user4 User + DB.Raw("select * from users WHERE name = ?", "user").First(&user3) + if user3.Id != user1.Id { + t.Errorf("Find first record with raw") + } + + DB.Raw("select * from users WHERE name = ?", "user").Last(&user4) + if user4.Id != user2.Id { + t.Errorf("Find last record with raw") + } +} + func TestUIntPrimaryKey(t *testing.T) { var animal Animal DB.First(&animal, uint64(1)) diff --git a/scope.go b/scope.go index 2a7eeea4..4a962062 100644 --- a/scope.go +++ b/scope.go @@ -329,7 +329,12 @@ func (scope *Scope) QuotedTableName() (name string) { // CombinedConditionSql return combined condition sql func (scope *Scope) CombinedConditionSql() string { - return scope.joinsSQL() + scope.whereSQL() + scope.groupSQL() + + joinSql := scope.joinsSQL() + whereSql := scope.whereSQL() + if scope.Search.raw { + whereSql = strings.TrimSuffix(strings.TrimPrefix(whereSql, "WHERE ("), ")") + } + return joinSql + whereSql + scope.groupSQL() + scope.havingSQL() + scope.orderSQL() + scope.limitAndOffsetSQL() } @@ -792,7 +797,7 @@ func (scope *Scope) joinsSQL() string { func (scope *Scope) prepareQuerySQL() { if scope.Search.raw { - scope.Raw(strings.TrimSuffix(strings.TrimPrefix(scope.CombinedConditionSql(), " WHERE ("), ")")) + scope.Raw(scope.CombinedConditionSql()) } else { scope.Raw(fmt.Sprintf("SELECT %v FROM %v %v", scope.selectSQL(), scope.QuotedTableName(), scope.CombinedConditionSql())) }