登录
首页 >  Golang >  Go问答

正确使用FirstOrCreate方法的示例

来源:stackoverflow

时间:2024-03-03 23:03:25 194浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《正确使用FirstOrCreate方法的示例》,涉及到,有需要的可以收藏一下

问题内容

我有以下简单的结构

type profile struct {
    gorm.model

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

如果不存在,我正在尝试插入

db.con.debug().where(db.profile{email: "[email protected]"}).assign(db.profile{lastlogin: time.now()}).firstorcreate(&profile)

我在日志中收到以下内容

(/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" = '[email protected]')) 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" = '[email protected]'))
[0 rows affected or returned ]

因此,即使在选择中找到 0 行,它也会尝试执行选择/更新。在我看来,我正在做正确的事。


解决方案


我认为您忘记创建表 db.createtable(&profile{})

这是一个工作示例:

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: "[email protected]"}).assign(profile{lastlogin: time.now()}).firstorcreate(&profile)
}

输出:

[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,'[email protected]','2018-09-25 09:47:35')
[1 rows affected or returned ]

希望这有帮助:)

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>