beego orm一对多 关联查询

版权声明:有问题可以私信我 https://blog.csdn.net/console__/article/details/87985433

models

type 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"`
}

数据库中数据

user表

在这里插入图片描述

Baby表

在这里插入图片描述

数据库操作

	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": ""
            }
        }
    ]
}

猜你喜欢

转载自blog.csdn.net/console__/article/details/87985433