drhs13583567608 2018-09-24 19:45
浏览 466
已采纳

如何正确使用FirstOrCreate

I have the following simple struct

type Profile struct {
    gorm.Model

    Email     string    `json:"email" sql:"not null;unique"`
    LastLogin time.Time `json:"lastlogin"`
}

I'm trying to make a insert if it doesn't exist via

  db.Con.Debug().Where(db.Profile{Email: "user@domain.com"}).Assign(db.Profile{LastLogin: time.Now()}).FirstOrCreate(&profile)

I get the following in my logs

(/Users/mzupan/go/src/gitlab.com/org/app/pkg/auth/login.go:182)
[2018-09-24 13:35:58]  [4.56ms]  SELECT * FROM "profiles"  WHERE "profiles"."deleted_at" IS NULL AND (("profiles"."email" = 'user@domain.com')) ORDER BY "profiles"."id" ASC LIMIT 1
[0 rows affected or returned ]

(/Users/mzupan/go/src/gitlab.com/org/app/pkg/auth/login.go:182)
[2018-09-24 13:35:58]  [1.77ms]  UPDATE "profiles" SET "last_login" = '2018-09-24 13:35:58', "updated_at" = '2018-09-24 13:35:58'  WHERE "profiles"."deleted_at" IS NULL AND (("profiles"."email" = 'user@domain.com'))
[0 rows affected or returned ]

So it's trying to do the select/update even though 0 rows are found in the select. Seems to me I'm doing the right thing.

  • 写回答

1条回答 默认 最新

  • duano3557 2018-09-25 02:49
    关注

    I think you forget to create the table db.CreateTable(&Profile{})

    Here is a working example:

    package main
    
    import (
        "time"
    
        "github.com/jinzhu/gorm"
        _ "github.com/jinzhu/gorm/dialects/sqlite"
    )
    
    type Profile struct {
        gorm.Model
    
        Email     string    `json:"email" sql:"not null;unique"`
        LastLogin time.Time `json:"lastlogin"`
    }
    
    func main() {
        db, err := gorm.Open("sqlite3", "test.db")
        if err != nil {
            panic("failed to connect database")
        }
        defer db.Close()
        // Create the table...
        // Read the doc at: http://doc.gorm.io/database.html#migration -> sec: Create Table
        db.CreateTable(&Profile{})
    
        var profile Profile
        db.Debug().Where(Profile{Email: "user@domain.com"}).Assign(Profile{LastLogin: time.Now()}).FirstOrCreate(&profile)
    }
    

    Out put:

    [2018-09-25 09:47:35]  [0.18ms]  INSERT INTO "profiles" ("created_at","updated_at","deleted_at","email","last_login") VALUES ('2018-09-25 09:47:35','2018-09-25 09:47:35',NULL,'user@domain.com','2018-09-25 09:47:35')
    [1 rows affected or returned ]
    

    Hope this help :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧