我想创建三个表:用户、事件、配对.

在配对表中将有三列:EventID、User1、User2. 因此,user1和user2都将通过id引用USERS表.

我知道如何在SQL中做到这一点,但我想try 使用ORM.我看过文档了,但我不知道怎么做

type User struct {
    Id       uint64 `gorm:"primarykey"`
    TGtag    string
    IsActive bool
}

type RCEvent struct {
    Id          uint64 `gorm:"primarykey"`
    DateStarted time.Time
    IsActive    bool
}

type Pair struct {
    EventId uint64
    UserID1 uint64
    UserID2 uint64
}

我试着用GORM-TAG做点什么,就像这样,但没有成功:

type User struct {
    Id       uint64 `gorm:"primarykey"`
    TGtag    string
    IsActive bool
}

type RCEvent struct {
    Id          uint64 `gorm:"primarykey"`
    DateStarted time.Time
    IsActive    bool
    Pairs       []Pair `gorm:"many2many:pair;"`
}

type Pair struct {
    EventId uint64 `gorm:"primarykey"`
    UserID1 uint64 `gorm:"primarykey"`
    UserID2 uint64 `gorm:"primarykey"`
}

此外,我try 了类似的操作,但得到了运行时错误

type User struct {
    Id       uint64 `gorm:"primarykey"`
    TGtag    string
    IsActive bool
}

type RCEvent struct {
    Id          uint64 `gorm:"primarykey"`
    DateStarted time.Time
    IsActive    bool
}

type Pair struct {
    Event   RCEvent
    User1 User //`gorm:"foreignkey:UserId"`
    User2 User //`gorm:"foreignkey:UserId"`
}
[error] failed to parse value &db.Pair{Event:db.RCEvent{Id:0x0, DateStarted:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), IsActive:false}, User1:db.User{Id:0x0, TGtag:"", IsActive:false}, User2:db.User{Id:0x0, TGtag:"", IsActive:false}}, got error invalid field found for struct untitledPetProject/internal/db.Pair's field Event: define a valid foreign key for relations or implement the Valuer/Scanner interface

推荐答案

要使用另一个 struct 作为外键,您应该将它的id作为另一个字段添加到目标 struct 中,对于您的 case ,这里是工作示例(使用gorm example):

package main

import (
    "log"
    "time"

    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type User struct {
    gorm.Model
    ID       uint64 `gorm:"primarykey"`
    TGtag    string
    IsActive bool
}

type RCEvent struct {
    gorm.Model
    ID          uint64 `gorm:"primarykey"`
    DateStarted time.Time
    IsActive    bool
}

type Pair struct {
    gorm.Model
    ID      uint64 `gorm:"primarykey"`
    EventID uint64
    Event   RCEvent
    User1ID uint64
    User1   User
    User2ID uint64
    User2   User
}

func main() {
    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    // Migrate the schema
    err = db.AutoMigrate(&User{})
    if err != nil {
        log.Fatal(err)
    }
    err = db.AutoMigrate(&RCEvent{})
    if err != nil {
        log.Fatal(err)
    }
    err = db.AutoMigrate(&Pair{})
    if err != nil {
        log.Fatal(err)
    }

    // Create
    user1 := User{ID: 2, TGtag: "mohammad"}
    user2 := User{ID: 3, TGtag: "ali"}
    event := RCEvent{ID: 2}
    pair := Pair{ID: 2, EventID: 2, Event: event, User1ID: 2, User1: user1, User2ID: 3, User2: user2}
    db.Create(&user1)
    db.Create(&user2)
    db.Create(&event)
    db.Create(&pair)

    // Read
    var user User
    db.First(&user, 3)                   // find product with integer primary key
    db.First(&user, "t_gtag = ?", "ali") // find product with code D42

    // Update - update product's price to 200
    db.Model(&user).Update("is_active", false)
    // Update - update multiple fields
    db.Model(&user).Updates(User{ID: 4, TGtag: "ahmad"}) // non-zero fields
    db.Model(&user).Updates(map[string]interface{}{"Id": 5, "TGtag": "hasan"})

    // Delete - delete product
    db.Delete(&user, 2)
}

Go相关问答推荐

try 用GitHub操作中的release标签更新version. go文件,但失败了

无法使用Segentio;S Kafka-Go连接到融合的Kafka

Json.Unmarshal() 和 gin.BindJson() 之间的区别

如何将Golang测试用例的测试覆盖率值与特定阈值进行比较

如何在 fyne-io/fyne 中设置文本的字母间距?

自定义 Fyne 自适应网格布局

甚至用天真的洗牌分配?

从Go中的随机日期开始以天为单位获取时间

读取非UTF8编码的文件内容并正确打印出来

Protobuf.Any - 从 json.RawMessage 解组

如果 transaction.Commit 对带有 postgres 连接的 SQL 失败,您是否需要调用 transaction.RollBack

在 GORM 中,如何在特定时区配置 autoCreateTime 和 autoUpdateTime?

使用 Golang SQL 驱动程序连接到snowflake

如何在 Golang 中使用具有相同名称或特定关键字的行或列重新排列/排序 CSV

函数调用中的类型参数panic

具有多个嵌入式 struct 的 Go MarshalJSON 行为

如何正确判断 io.Reader 是否为零?

传递上下文的最佳方式

将基本 HTTP AUth 用户/密码凭据存储在 GO 中,无需外部包

gopls 为 github.com/Shopify/sarama 返回错误gopls: no packages returned: packages.Load error