Heim  >  Fragen und Antworten  >  Hauptteil

Golang GORM implementiert den Datenabruf und die Verknüpfungstabellenabfrage von Viele-zu-Viele-Beziehungen

Ich verwende Golang 1.19 und ORM als GORM. Ich muss ein Produkt mithilfe der Kategorie-ID abrufen. Die Produkttabelle und die Kategorietabelle sind an eine Viele-zu-Viele-Beziehung gebunden. Die dritte Tabelle ist also „product_categories“.

Wenn eine Abrufanfrage eine Kategorie-ID enthält, muss ich das Produkt mit dieser Kategorie-ID abrufen.

Schauen Sie sich die Modellstruktur unten an,

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

Ich verwende eine alternative Methode, um dies zu erreichen. Es funktioniert gut, aber ich denke, dass es nicht der beste Ansatz ist, wenn es um viele zu viele geht. Ich rufe zuerst ProductCategory 然后循环它并获取 product id 然后将其添加到切片中,然后使用这些产品 id 检索 products ab.

Siehe meinen Code unten,

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
}

Was ist der beste Weg, um mithilfe der Viele-zu-Viele-Beziehung von GORM Produkte zu erhalten, die für mein Szenario geeignet sind?

P粉908138620P粉908138620289 Tage vor424

Antworte allen(1)Ich werde antworten

  • 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)

    Antwort
    0
  • StornierenAntwort