[英]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.