Golang GORM implements data retrieval and join table query of many-to-many relationships
P粉908138620
P粉908138620 2024-01-04 13:57:53
0
1
422

I use golang 1.19 and ORM as GORM. I need to retrieve a product using category ID. The product table and category table are bound to a many-to-many relationship. So the third table is product_categories.

What I need to do is when a get request comes with a category id, I need to retrieve the product with that category id.

View the model structure below,

// 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:"-"`
}

I'm using an alternative method to achieve this. It works fine, but I think it's not the best approach when it comes to many-to-many. I first retrieve the ProductCategory then loop over it and get the product id then add it to the slice and then use those product ids to retrieve the products .

Check out my code below,

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
}

What is the best way to get products suitable for my scenario using GORM's many-to-many relationship?

P粉908138620
P粉908138620

reply all(1)
P粉446800329

I can't verify as I don't have the setup for this, but based on https://gorm.io/docs/many_to_many.html and the idea of ​​preloading, you should be able to create a file with the desired ID category entity, and then preload products on that category, for example:

category := models.Category{ID: id}
err := q.Model(&Category{}).Preload("Products").Find(&category)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!