worm支持表之间的inner join、left join、right join关联查询。您可使用Get()或Scan()方法获取一条关联查询的结果。若需要获取多条关联查询的结果,您可以使用Find()方法。
定义一个user表以及相应的实体类:
//建表语句
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`passwd` varchar(32) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`updated` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
type User struct {
Id int64 `db:"id;autoincr"`
Name string `db:"name"`
Age int64 `db:"age"`
Passwd string `db:"passwd"`
Created time.Time `db:"created;n_update"`
}
func (ent *User) TableName() string {
return "user"
}
定义一个book表以及相应的实体类:
CREATE TABLE `book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`author` bigint(20) NOT NULL DEFAULT '0',
`name` varchar(16) NOT NULL DEFAULT '',
`price` decimal(11,2) NOT NULL DEFAULT 0.0,
PRIMARY KEY (`id`)
);
type Book struct {
Id int64 `db:"id;autoincr"`
Name string `db:"name"`
Author int64 `db:"author"`
Price float32 `db:"price"`
}
func (ent *Book) TableName() string {
return "book"
}
要进行关联查询,首先定义一个worm.Model对象,并执行worm.Model.TableAlias()方法来创建一个worm.DbJoint对象。然后执行tb.Join()方法进行关联查询:
func demoJoinScan() {
var user User
var book Book
tb := worm.Model(&user).Select("id","name","age").TableAlias("u")
tb.Join(&book, "b", "b.author=u.id", "name")
_, err := tb.Where("u.id=?", 1).Scan()
if err != nil{
log.Error(err)
return
}
}
//select u.id as u_id,u.name as u_name,u.age as u_age,b.name as b_name from users u join book b on b.author=u.id where u.id=1 limit 1
说明:
使用Get()方法查询时, 需要首先定义一个组合实体类,该组合实体类包含了关联查询中的用到的实体类。
func demoJoinGet() {
type UserBook struct {
User
Book
}
var data UserBook
tb := worm.Model(&User{}).Select("id","name","age").TableAlias("u")
tb.Join(&Book{}, "b", "b.author=u.id", "name")
_, err := tb.Where("u.id=?", 1).Get(&data)
if err != nil{
log.Error(err)
return
}
}
//select u.id as u_id,u.name as u_name,u.age as u_age,b.name as b_name from users u join book b on b.author=u.id where u.id=1 limit 1
func demoJoinFind() {
type UserBook struct {
User
Book
}
var datas []UserBook
tb := worm.Model(&User{}).Select("id","name","age").TableAlias("u")
tb.Join(&Book{}, "b", "b.author=u.id", "name", "price")
err := tb.Where("u.id>?", 0).Find(&datas)
if err != nil{
log.Error(err)
return
}
}
//select u.id as u_id,u.name as u_name,u.age as u_age,b.name as b_name,b.price as b_price from users u join book b on b.author=u.id where u.id>0
func demoLeftJoinFind() {
type UserBook struct {
User
Book
}
var datas []UserBook
tb := worm.Model(&User{}).Select("id","name","age").TableAlias("u")
tb.LeftJoin(&Book{}, "b", "b.author=u.id", "name")
err := tb.Where("u.id>?", 0).Find(&datas)
if err != nil{
log.Error(err)
return
}
}
//select u.id as u_id,u.name as u_name,u.age as u_age,b.name as b_name from users u left join book b on b.author=u.id where u.id>0