Add Joins support

This commit is contained in:
Jinzhu 2014-01-04 14:23:55 +08:00
parent d64f4825d7
commit 13302ba410
3 changed files with 38 additions and 4 deletions

View File

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

4
do.go
View File

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

View File

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