首頁  >  文章  >  後端開發  >  如何查詢關係的嵌入值等於特定值的模型?

如何查詢關係的嵌入值等於特定值的模型?

WBOY
WBOY轉載
2024-02-09 18:39:08916瀏覽

如何查詢關係的嵌入值等於特定值的模型?

在開發和設計資料庫模型時,有時我們需要查詢關係中的嵌入值是否等於特定值。這個問題在實際應用中經常遇到,但解決起來可能並不容易。在本文中,我將向大家介紹一個有效的方法來查詢關係的嵌入值是否等於特定值的模型。無需擔心,我會用簡潔易懂的語言解釋清楚,幫助您快速理解並應用到實際開發中。讓我們一起來看看吧!

問題內容

我有兩個不同的模型(carstypes),它們彼此相關(屬於關係),其中兩個模型都有一個嵌入式struct 用於公共資料(post)。我想檢索某些 types,但只想收到 postcars 值等於某個值的答案。

shorty說,根據下面的模型,我想找到所有types,其中cars.post.published等於true。

模型

type post struct {
  published bool
}

type car struct {
  gorm.model
  brand string
  post post `gorm:"embedded"`
}

type type struct {
  gorm.model
  name string
  carid uint32
  car car
  post post `gorm:"embedded"`
}

使用 db.preload("car").find(&type) 我能夠在答案物件中取得 car 值。如果我在car 結構上使用where() 函數(即where(car{brand: "volvo"}) 我可以透過brand 取得值,但當使用post 時(即where(car{post: post {published: true})) 它只會傳回所有內容。

我最好使用需要查詢的主模型作為 where() 函數的基礎。例如:

q := Type{Car: Car{Post: Post{Published: true}}}
db.Preload("Car").Where(q).Find(&Type)

...但這似乎不起作用。如何在不使用原始 sql 生成器的情況下實現這樣的查詢?

解決方法

我能夠透過以下方式解決您的問題。首先,我將分享程式碼,然後我將介紹值得解釋的要點。

package main

import (
    "fmt"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type Post struct {
    Published bool
}

type Car struct {
    gorm.Model
    Brand  string
    TypeID int
    Type   Type
    Post   Post `gorm:"embedded"`
}

type Type struct {
    gorm.Model
    Name  string
    CarID int
    Post  Post `gorm:"embedded"`
}

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

    // uncomment these to seed data
    // db.Create(&Car{Brand: "Tesla", Type: Type{Name: "SUV", Post: Post{Published: true}}, Post: Post{Published: true}})
    // db.Create(&Car{Brand: "Ford", Type: Type{Name: "City", Post: Post{Published: false}}, Post: Post{Published: false}})

    var cars []Car
    if err := db.Debug().Model(&Car{}).Preload("Type").Where(&Car{Post: Post{Published: true}}).Find(&cars).Error; err != nil {
        panic(err)
    }
    for _, v := range cars {
        fmt.Println(v.Type.Name)
    }
}

現在,讓我分享一些見解。

結構體定義

我稍微改變了它來處理這個場景。我從 type 結構中刪除了 car 字段,並在 car 結構定義中添加了其對應項。

設定與種子

然後,我透過 gorm 設定了資料庫連接。我將程式碼中定義的模型與資料庫中存在的關係同步。為了演示,我手動播種了一些虛擬資料。

讀取邏輯

然後,我執行查詢來取得相關資料。我使用了以下方法:

  1. debug:用來記錄實際的sql語句
  2. model:用來指定我們要處理的關係
  3. preload:用於載入type關聯
  4. where:用於指定條件(在我們的例子中,過濾器位於嵌入結構上)
  5. find:用於將結果對應到變數

請告訴我這是否有助於解決您的問題,謝謝!

以上是如何查詢關係的嵌入值等於特定值的模型?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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