dtoaillwk759656786 2019-03-05 23:22
浏览 44
已采纳

使用“具有一个”关联进行查询(一对一)

I'm playing a bit with Gorm while I'm trying to decide which ORM library fit the most for my needs.

Important to mention that I'm currently working with Sqlite.

Following the guide I created two structs:

  type Color struct {
    gorm.Model
    UserID uint
    Name   string
}

//User struct define a basic user model
type User struct {
    gorm.Model
    Username     string
    Email        string
    FirstName    string
    LastName     string
    Password     string
    CreationDate time.Time
    DOB          time.Time
    IgnoreMe     int   `gorm:"-"` // Ignore this field
    Color        Color `gorm:"foreignkey:ColorRefer"`
    ColorRefer   uint
}

when I'm creating a DB with

func CreateTables() {
user := dm.User{}
color := dm.Color{}
GormDB.CreateTable(&color)
GormDB.CreateTable(&user)
GormDB.Model(&user).AddForeignKey("ColorRefer", "colors(id)", "CASCADE", "CASCADE")

}

or with:

func CreateTables() {
    GormDB.AutoMigrate(&dm.User{},&dm.Color{})
}

Sadly it's not working as I would of expect and create the foreign key automatically, but it's works when I do it manually.

My main problem is when I'm trying to query Users

//QueryByStructExample query users table by the struct non-zero (non-default) fields.
    func QueryByStructExample(userStruct dm.User) []dm.User {
        var results []dm.User
        GormDB.Where(userStruct).Find(&results)
        return results
    }

I created the following function in a try to query users by email with the color property which is my color struct and I tried to play with a lot with the Model,Related and the Association functions, and nothing seems to work and (I'm avoiding to use join by purpose). The end result is that it query my User but without the color (only with the ID in my colorRefer)

any suggestion?

展开全部

  • 写回答

1条回答 默认 最新

  • dthok9648 2019-03-06 00:58
    关注

    Do you mean to preload the Color struct? If yes did you try to query it like that

    GormDB.Preload('Color').Where(userStruct).Find(&results)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 点云密度大则包围盒小
  • ¥15 nginx使用nfs进行服务器的数据共享
  • ¥15 C#i编程中so-ir-192编码的字符集转码UTF8问题
  • ¥15 51嵌入式入门按键小项目
  • ¥30 海外项目,如何降低Google Map接口费用?
  • ¥15 fluentmeshing
  • ¥15 手机/平板的浏览器里如何实现类似荧光笔的效果
  • ¥15 盘古气象大模型调用(python)
  • ¥15 传人记程序做的plc 485从机程序该如何写
  • ¥15 已知手指抓握过程中掌指关节、手指各关节和指尖每一帧的坐标,用贝塞尔曲线可以拟合手指抓握的运动轨迹吗?