dtoaillwk759656786 2019-03-06 07: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 08: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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?