亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Golang GORM實(shí)現(xiàn)多對(duì)多關(guān)系的數(shù)據(jù)檢索與聯(lián)接表查詢
P粉908138620
P粉908138620 2024-01-04 13:57:53
0
1
723

我使用 golang 1.19 和 ORM 作為 GORM。我需要使用類別 ID 檢索產(chǎn)品。產(chǎn)品表和類別表綁定多對(duì)多關(guān)系。所以第三個(gè)表是product_categories。

我需要做的是,當(dāng) get 請(qǐng)求帶有類別 id 時(shí),我需要檢索具有該類別 id 的產(chǎn)品。

在下面查看模型結(jié)構(gòu),

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

我正在使用替代方法來(lái)實(shí)現(xiàn)這一目的。它工作得很好,但我認(rèn)為當(dāng)涉及到多對(duì)多時(shí),這不是最好的方法。我首先檢索 ProductCategory 然后循環(huán)它并獲取 product id 然后將其添加到切片中,然后使用這些產(chǎn)品 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 的多對(duì)多關(guān)系獲取適合我的場(chǎng)景的產(chǎn)品的最佳方式是什么?

P粉908138620
P粉908138620

全部回復(fù)(1)
P粉446800329

我無(wú)法驗(yàn)證,因?yàn)槲覜](méi)有這方面的設(shè)置,但基于 https://gorm.io/docs/many_to_many.html 和預(yù)加載的想法,您應(yīng)該能夠創(chuàng)建具有所需 ID 的類別實(shí)體,然后預(yù)加載該類別上的產(chǎn)品,例如:

category := models.Category{ID: id}
err := q.Model(&Category{}).Preload("Products").Find(&category)
最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板