首页 >后端开发 >Golang >GORM:一张表的两个外键

GORM:一张表的两个外键

WBOY
WBOY转载
2024-02-09 18:33:081119浏览

GORM:一张表的两个外键

在使用GORM进行数据库操作时,我们常常会遇到一张表需要同时关联两个外键的情况。这种情况下,如何正确地设置和使用外键成为了一个需要解决的问题。在本文中,php小编鱼仔将为大家详细介绍如何使用GORM来处理一张表的两个外键,以及相关的注意事项和实际应用案例。通过学习本文,相信大家能够更好地理解和运用GORM进行数据库操作。

问题内容

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

在配对表中将有三列:eventId、user1、user2。 所以user1、user2都会通过id引用Users表。

我知道如何在 sql 中执行此操作,但我想尝试使用 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 标签做一些事情,比如这样,但没有成功:

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"`
}

另外,我尝试了类似的方法并遇到了运行时错误

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

解决方法

要使用另一个结构作为外键,您应该将其 id 添加为目标结构中的另一个字段,对于您的情况,这里是工作示例(使用 gorm 示例):

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)
}

以上是GORM:一张表的两个外键的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除