美文网首页
GORM 关联查询用法

GORM 关联查询用法

作者: 会飞一下 | 来源:发表于2019-07-23 14:30 被阅读0次

以查询用户列表, 以及用户的详情 , 文章为例
定义结构体

type User struct {
    Id         uint        `gorm:"primary_key" json:"id"`
    Username   string      `gorm:"unique_index" json:"username"`
    Password   string      `json:"-"`
    State      string      `json:"state"`
    CreatedAt  time.Time   `json:"created_at"`
    UpdatedAt  time.Time   `json:"updated_at"`
    DeletedAt  *time.Time  `sql:"index" json:"deleted_at"`
    UserDetail *UserDetail `json:"user_detail"`
    Posts      []Post      `json:"posts"`
}

type UserDetail struct {
    Id        uint       `gorm:"primary_key" json:"id"`
    UserId    uint       `json:"user_id"`
    NickName  string     `json:"nick_name"`
    Sex       int        `json:"sex"`
    Avatar    string     `json:"avatar"`
    Profile   string     `json:"profile"`
    CreatedAt time.Time  `json:"created_at"`
    UpdatedAt time.Time  `json:"updated_at"`
    DeletedAt *time.Time `sql:"index" json:"deleted_at"`
}
type Post struct {
    Id        uint       `gorm:"primary_key" json:"id"`
    UserId    uint       `json:"user_id"`
    Title     string     `json:"title"`
    Body      string     `json:"body"`
    Link      string     `json:"link"`
    CreatedAt time.Time  `json:"created_at"`
    UpdatedAt time.Time  `json:"updated_at"`
    DeletedAt *time.Time `sql:"index" json:"deleted_at"`
}
查找出有发表过文章的所有用户, 并展示出用户的详细资料及用户最后发表的一偏文章

``` golang

func Search(c *gin.Context) {

    page, limit, offset, keyword := listInit(c)

    var Data []User
    var Count int

    Orm.Debug().Model(&Data).
        Preload("UserDetail").
        Preload("Posts", func( query *gorm.DB) *gorm.DB {
            return query.Where("id >1 ").Order("id desc ").Limit(1)
        }).
        Where("username like ?", "%"+keyword+"%").
        Where("EXISTS (?) ",
            Orm.Table("post").
            Where("user.id = post.user_id").
            QueryExpr()).
        Count(&Count).
        Limit(limit).
        Offset(offset).
        Order("id asc").
        Find(&Data)

    c.JSON(200, gin.H{
        "data":  Data,
        "count": Count,
        "page":  page,
        "limit": limit,
    })

}

相关文章

网友评论

      本文标题:GORM 关联查询用法

      本文链接:https://www.haomeiwen.com/subject/xgwolctx.html