Golang GORM实现多对多关系的数据检索与联接表查询
P粉908138620
P粉908138620 2024-01-04 13:57:53
0
1
429

我使用 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粉908138620
P粉908138620

全部回复(1)
P粉446800329

我无法验证,因为我没有这方面的设置,但基于 https://gorm.io/docs/many_to_many.html 和预加载的想法,您应该能够创建具有所需 ID 的类别实体,然后预加载该类别上的产品,例如:

category := models.Category{ID: id}
err := q.Model(&Category{}).Preload("Products").Find(&category)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!