diff --git a/README.md b/README.md index 6491b933..b28eb822 100644 --- a/README.md +++ b/README.md @@ -886,6 +886,23 @@ rows, err := db.Table("orders").Select("date(created_at) as date, sum(amount) as for rows.Next() { ... } + +type Result struct { + Date time.Time + Total int64 +} +db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Having("sum(amount) > ?", 100).Scan(&results) +``` + +## Joins + +```go +rows, err := db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Rows() +for rows.Next() { + ... +} + +db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Scan(&results) ``` ## Run Raw SQL @@ -970,7 +987,6 @@ db.Where("email = ?", "x@example.org").Attrs(User{RegisteredIp: "111.111.111.111 ``` ## TODO -* Scan * Support plugin BeforeQuery BeforeSave @@ -998,7 +1014,6 @@ db.Where("email = ?", "x@example.org").Attrs(User{RegisteredIp: "111.111.111.111 * Getter/Setter share or not? transaction? * Github Pages -* Joins * Includes * AlertColumn, DropColumn, AddIndex, RemoveIndex diff --git a/do.go b/do.go index 19518fe1..6c818eaa 100644 --- a/do.go +++ b/do.go @@ -707,11 +707,11 @@ func (s *Do) havingSql() string { } func (s *Do) joinsSql() string { - return "" + return s.search.joinsStr + " " } func (s *Do) combinedSql() string { - return s.whereSql() + s.groupSql() + s.havingSql() + s.orderSql() + s.limitSql() + s.offsetSql() + return s.joinsSql() + s.whereSql() + s.groupSql() + s.havingSql() + s.orderSql() + s.limitSql() + s.offsetSql() } func (s *Do) createTable() *Do { diff --git a/gorm_test.go b/gorm_test.go index 609fb230..3c7e57db 100644 --- a/gorm_test.go +++ b/gorm_test.go @@ -1591,6 +1591,25 @@ func TestGroup(t *testing.T) { } } +func TestJoins(t *testing.T) { + type result struct { + Name string + Email string + } + + user := User{ + Name: "joins", + Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}}, + } + db.Save(&user) + + var results []result + db.Table("users").Select("name, email").Joins("left join emails on emails.user_id = users.id").Where("name = ?", "joins").Scan(&results) + if len(results) != 2 || results[0].Email != "join1@example.com" || results[1].Email != "join2@example.com" { + t.Errorf("Should find all two emails with Join") + } +} + func NameIn1And2(d *DB) *DB { return d.Where("name in (?)", []string{"1", "2"}) }