首頁  >  問答  >  主體

Golang GORM實現多對多關係的資料檢索與聯接表查詢

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

我需要做的是,當 get 請求帶有類別 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 的多對多關係獲取適合我的場景的產品的最佳方式是什麼?

P粉908138620P粉908138620289 天前421

全部回覆(1)我來回復

  • P粉446800329

    P粉4468003292024-01-05 09:38:22

    我無法驗證,因為我沒有這方面的設置,但基於 https://gorm.io/docs/many_to_many.html 和預先載入的想法,您應該能夠建立具有所需ID的類別實體,然後預先載入該類別上的產品,例如:

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

    回覆
    0
  • 取消回覆