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

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行