首頁  >  文章  >  後端開發  >  Gorm 根據嵌套表的條件從表中取得所有數據

Gorm 根據嵌套表的條件從表中取得所有數據

王林
王林轉載
2024-02-10 12:42:08569瀏覽

Gorm 根据嵌套表的条件从表中获取所有数据

php小編西瓜為你介紹一個高效的資料取得方法-Gorm。 Gorm是一個基於Golang的ORM庫,它可以輕鬆地與資料庫互動。在使用Gorm時,我們可以根據嵌套表的條件從表中獲取所有數據,而無需繁瑣的手動查詢。這種方法不僅簡化了程式碼,也提高了查詢效率,讓開發人員更方便操作資料。無論是初學者還是有經驗的開發者,都可以透過使用Gorm輕鬆地實現資料擷取功能。

問題內容

我有一個如下 golang 結構的表:

order {
  id
  transactionid
  transaction
}

transaction {
  id
  profileid
  profile
}

profile {
  id
  accountid
  account
}

如何透過gorm取得所有帶有帳戶id條件的訂單? 我已經嘗試過:

var orders []*Order
 res := r.db.
        Joins("Transaction").
        Preload("Transaction.Profile").
        Where("Transaction.Profile.account_id = 1").
        Find(&orders)

但是它不起作用。

解決方法

該解決方案應該基於您提供的結構定義來運作。首先,讓我展示程式碼,然後我將完成每個步驟:

package main

import (
    "fmt"

    _ "github.com/lib/pq"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type Order struct {
    Id            int
    TransactionId int
    Transaction   Transaction
}

type Transaction struct {
    Id        int
    ProfileId int
    Profile   Profile
}

type Profile struct {
    Id        int
    AccountId int
    Account   Account
}

type Account struct {
    Id int
}

func main() {
    dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        panic(err)
    }

    db.AutoMigrate(&Account{})
    db.AutoMigrate(&Profile{})
    db.AutoMigrate(&Transaction{})
    db.AutoMigrate(&Order{})

    db.Create(&Account{})
    db.Create(&Profile{AccountId: 1})
    db.Create(&Transaction{ProfileId: 1})
    db.Create(&Order{TransactionId: 1})

    // order + transaction + profile + account
    var order Order
    db.Debug().Preload("Transaction.Profile.Account").Joins("inner join transactions t on orders.transaction_id = t.id").Joins("inner join profiles p on p.id = t.profile_id").Joins("inner join accounts a on p.account_id = a.id").First(&order, "a.id = ?", 1)
    fmt.Println(order)
}

讓我們仔細看看程式碼。

結構定義

這裡沒有任何改變。聲明結構時,請務必了解 gorm 約定,因為 gorm 將基於此建立關係、外鍵和約束。

準備資料庫

在這裡,您可以找到與 postgres 的連接、用於同步表的自動遷移命令以及一些虛擬資料的插入。

查詢

這裡,我們使用了 go 的 gorm 套件提供的許多方法。讓我們在一個簡短的清單中回顧一下它們:

  • debug:它將原始 sql 查詢列印到控制台。處理複雜查詢時非常有用
  • preload:載入相關實體,但不將它們包含在 gorm 產生的最終查詢中
  • joins:它指定在 join 子句中必須引用哪些表。使用 joins 我們將該子句加入查詢。
  • first:它既用於只取得一筆記錄,也用於指定一些篩選器,例如我們的範例(例如 a.id = ?)。

如果這可以解決您的問題,請告訴我,謝謝!

以上是Gorm 根據嵌套表的條件從表中取得所有數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除