一对多

model
ype User struct {
Id int64 json:"id"
Name string json:"name,omitempty" orm:"size(50)"
Passwords string json:"passwords" orm:"size(32)"
Baby []Baby json:"baby" orm:"reverse(many)"
}
type Baby struct {
Id int64
Name string json:"name" orm:"size(50)"
User
User json:"user" orm:"rel(fk);index"
}

数据库查询
o:= orm.NewOrm()
o.QueryTable("tb_user").Filter("id" ,user.Id).One(user)
o.LoadRelated(user,"Baby")

返回结果

{
"id": 2,
"name": "test",
"passwords": "123456",
"baby": [
{
"Id": 1,
"name": "慕青",
"user": {
"id": 2,
"passwords": ""
}
},
{
"Id": 2,
"name": "木木",
"user": {
"id": 2,
"passwords": ""
}
}
]
}

多对多

models 表结构
// User table 用户表,与用户组表多对多关系
type User struct {
Id int
UserName string orm:"unique"
Department string
Email string
Groups []Group orm:"rel(m2m)" //多对多
}
// Group table 用户组表,与用户表多对多关系
type Group struct {
Id int
GroupName string orm:"unique"
Introduce string
Users []
User orm:"reverse(many)" //反向多对多
}

添加
o := orm.NewOrm()
u1 := User{UserName: "zhangszan"}
u2 := User{UserName: "lisi"}
g1 := Group{GroupName: "g1"}
g2 := Group{GroupName: "g2"}
o.InsertMulti(2, []User{u1, u2})
o.InsertMulti(2, []Group{g1, g2})
m2mu1 := o.QueryM2M(&u1, "Groups")
m2mu2 := o.QueryM2M(&u2, "Groups")
m2mu1.Add(&g1)
m2mu1.Add(&g2)
m2mu2.Add(&g2)

删除方法和添加方法相似,将add改成Remove即可。另外还是clear等等

查询
o := orm.NewOrm()
u := new(User)
u.Id = 1
o.LoadRelated(u, "Groups")