簡體   English   中英

Golang GORM 數據檢索與連接表的多對多關系

[英]Golang GORM data retrieve for many to many relationship with join table

我正在使用 golang 1.19 和 ORM 作為 GORM。 我需要使用類別 ID 檢索產品。 產品表和類別表以多對多關系綁定。 所以第 3 個表是 product_categories。

我需要做的是當獲取請求帶有類別 ID 時,我需要檢索具有該類別 ID 的產品。

在下面尋找模型構造器,

// Product model
// Categories many2many:product_categories

type Product struct {
    ID               uint           `gorm:"primarykey" json:"id"`
    Slug             string         `gorm:"unique;size:255;" json:"slug"`
    Title            string         `gorm:"size:255;not null" json:"title"`
    Code             string         `gorm:"size:255;not null" json:"code"`
    BrandID          uint           `json:"-"`
    Brand            Brand          `json:"brand"`
    ShortDescription string         `gorm:"not null" json:"short_description"`
    Description      string         `json:"description"`
    Price            uint           `gorm:"not null" json:"price"`
    Quantity         uint           `json:"qnt"`
    DiscountPrice    uint           `json:"discount_price"`
    Categories       []Category     `gorm:"many2many:product_categories;" json:"categories"`
    Attributes       []Attribute    `json:"attributes"`
    ProductImages    []ProductImage `json:"product_images"`
    CreatedAt        time.Time      `json:"-"`
    UpdatedAt        time.Time      `json:"-"`
}
// Category model
// Products many2many:product_categories

type Category struct {
    ID        uint      `gorm:"primarykey" json:"id"`
    Name      string    `gorm:"size:255;not null" json:"name"`
    Icon      string    `gorm:"size:255;not null" json:"icon"`
    Image     string    `gorm:"size:255;not null" json:"image"`
    Weight    int32     `gorm:"AUTO_INCREMENT" json:"weight"`
    Products  []Product `gorm:"many2many:product_categories;" json:"products"`
    CreatedAt time.Time `json:"-"`
    UpdatedAt time.Time `json:"-"`
}

// ProductCategory Model
// This table auto generate with gorm

type ProductCategory struct {
    CategoryID int  `gorm:"primaryKey" json:"-"`
    ProductID  uint `gorm:"primaryKey" json:"-"`
}

我正在使用替代方法來解決問題。 它工作正常,但我認為當涉及到多對多時,這不是最好的方法。 我首先檢索ProductCategory ,然后對其進行循環並獲取product id ,然后將其添加到切片中,然后使用這些產品 ID 檢索products

在下面查看我的代碼,

func (q *Queries) GetProductsbyCat(id uint) ([]models.Product, error) {
    // Define products variable and product_cat variable
    products := []models.Product{}
    product_cats := []models.ProductCategory{}

    // Retrieve product_cat and assigned to variable
    err := q.Model(&product_cats).Limit(10).Find(&product_cats, "category_id = ?", id).Error
    if err != nil {
        // Return empty object and error.
        return nil, err
    }

    // define products ids slice
    productIds := []int{}
    // loop product cats and append product id's to productids variable
    for _, v := range product_cats {
        productIds = append(productIds, int(v.ProductID))
    }

    // Retrieve products
    err = q.Model(&products).Order("id desc").Preload("ProductImages").Find(&products, productIds).Error
    if err != nil {
        // Return empty object and error.
        return nil, err
    }

    return products, nil
}

使用與 GORM 的多對多關系為我的場景獲取產品的最佳方式是什么?

我無法驗證,因為我沒有為此設置,但基於https://gorm.io/docs/many_to_many.html和預加載的想法,你應該能夠創建一個類別實體所需的 ID,然后預加載該類別的產品,例如:

category := models.Category{ID: id}
err := q.Model(&Category{}).Preload("Products").Find(&category)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM