golang基礎-Postgresql-ORM框架github.com/go-pg/pg學習四(其他)
阿新 • • 發佈:2018-12-10
首先看下資料庫中的資料
go=# select * from users; id | name | emails ----+-------+---------------------------------- 1 | admin | ["[email protected]", "[email protected]"] 2 | root | ["[email protected]", "[email protected]"] (2 rows) go=# select * from storys; id | title | author_id ----+------------+----------- 1 | Cool story | 1 (1 row)
2個model是User、Story
type User struct {
Id int64
Name string
Emails []string
tableName struct{} `sql:"users"`
}
type Story struct {
Id int64
Title string
AuthorId int64
Author *User
tableName struct{} `sql:"storys"`
}
通過主鍵查詢
// Select user by primary key. user := &User{Id: 1} err := db.Select(user) if err != nil { panic(err) } fmt.Println(user)
輸出
User(1 admin [[email protected] [email protected]])
查詢所有
// Select all users.
var users []User
err = db.Model(&users).Select()
if err != nil {
panic(err)
}
fmt.Println(users)
輸出如下:
[User(1 admin [[email protected] [email protected]]) User(2 root [[email protected] [email protected]])]
關聯查詢
我們可以按條件關聯查詢
// Select story and associated author in one query
story := new(Story)
err = db.Model(story).
Relation("Author").
Where("story.id = ?", 1).
Select()
if err != nil {
panic(err)
}
fmt.Println(story)
輸出如下:
Story<1 Cool story User(1 admin [[email protected] [email protected]])>
我們還可以查詢所有
func main() {
db:=connet()
var storys []Story
err:=db.Model(&storys).Column("story.*").Relation("Author").Select()
if err!=nil{
panic(err)
}
fmt.Println(storys)
}
測試這個功能時候,往資料庫storys添加了一條記錄
go=# select * from storys;
id | title | author_id
----+------------+-----------
1 | Cool story | 1
2 | cool | 1
(2 rows)
輸出如下:
[Story<1 Cool story User(1 admin [[email protected] [email protected]])> Story<2 cool User(1 admin [[email protected] [email protected]])>]
查詢是否存在、個數
func main() {
db:=connet()
count,err:=db.Model(&User{}).Count()
if err!= nil{
panic(err)
}
exists,err:=db.Model(&User{}).Where("name=?","admin").Exists()
if err!= nil{
panic(err)
}
fmt.Println(exists)
fmt.Println(count)
}
輸出如下:
true
2
ForEach用法
func main() {
db:=connet()
db.Model(&User{}).OrderExpr("id ASC").ForEach(func(b *User) error{
fmt.Println(b)
return nil
})
}
輸出如下:
User(1 admin [[email protected] [email protected]])
User(2 root [[email protected] [email protected]])
Relation一
func main() {
db:=connet()
var story Story
err:=db.Model(&story).Column("story.*").Relation("Author", func(query *orm.Query) (*orm.Query, error) {
return query.Where("title='cool'"),nil
}).First()
if err!=nil{
panic(err)
}
fmt.Println(story)
}
輸出結果如下:
Story<2 cool User(1 admin [[email protected] [email protected]])>
或者如下
Relation二
func main() {
db:=connet()
var storys []Story
err:=db.Model(&storys).Column("story.*").Relation("Author").Select()
if err!=nil{
panic(err)
}
fmt.Println(storys)
}
輸出結果如下:
[Story<1 Cool story User(1 admin [[email protected] [email protected]])> Story<2 cool User(1 admin [[email protected] [email protected]])>]