GORM: two foreign keys to a table

WBOY
Release: 2024-02-09 18:33:08
forward
1078 people have browsed it

GORM: two foreign keys to a table

When using GORM for database operations, we often encounter situations where a table needs to be associated with two foreign keys at the same time. In this case, how to correctly set and use foreign keys becomes a problem that needs to be solved. In this article, PHP editor Yuzai will introduce in detail how to use GORM to process two foreign keys of a table, as well as related precautions and practical application cases. By studying this article, I believe everyone can better understand and use GORM for database operations.

Question content

I want to create three tables: users, events, and pairs.

There will be three columns in the matching table: eventId, user1, user2. So user1 and user2 will reference the Users table through id.

I know how to do this in sql, but I want to try using an ORM. I've read the documentation but I don't know how to do this

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
}
Copy after login

I tried doing something with the gorm tag, like this, but without success:

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"`
}
Copy after login

Also, I tried something similar and got a runtime error

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"`
}
Copy after login
[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
Copy after login

Workaround

To use another structure as foreign key you should add its id as another field in the target structure, for your case here is the working example (using 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)
}
Copy after login

The above is the detailed content of GORM: two foreign keys to a table. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!