2019-03-06 07:22
浏览 43


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 {
    UserID uint
    Name   string

//User struct define a basic user model
type User struct {
    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.Model(&user).AddForeignKey("ColorRefer", "colors(id)", "CASCADE", "CASCADE")


or with:

func CreateTables() {

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
        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条回答 默认 最新

相关推荐 更多相似问题