亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 GORM 以多對多關系連接兩個表?

如何使用 GORM 以多對多關系連接兩個表?

Go
拉莫斯之舞 2023-07-31 15:51:43
我的產品和類別表之間有多對多關系。我想檢索所有產品及其類別。type Product struct {    ProductID       int          `gorm:"column:product_id;primary_key" json:"product_id"`    Name            string       `gorm:"column:name" json:"name"`    Description     string       `gorm:"column:description" json:"description"`    Categories      []Category   `gorm:"many2many:product_category;foreignkey:product_id;association_foreignkey:category_id;association_jointable_foreignkey:category_id;jointable_foreignkey:product_id;"`}type Category struct {    CategoryID   int         `gorm:"column:category_id;primary_key" json:"category_id"`    Name         string      `gorm:"column:name" json:"name"`    Description  null.String `gorm:"column:description" json:"description"`    Products     []Product   `gorm:"many2many:product_category;foreignkey:category_id;association_foreignkey:product_id;association_jointable_foreignkey:product_id;jointable_foreignkey:category_id;"`}下面的代碼返回categorie_id 3的所有產品,但這些產品的類別切片為空var products  []model.Productcat := model.Category{}s.db.First(&cat, "category_id = ?", 3)err :=  s.db.Model(&cat).Related(&products, "Products").Error我嘗試了以下代碼,但沒有返回任何內容var products  []model.Productvar cat       [] model.Categoryerr :=  s.db.Model(&cat).Related(&products, "Products").Error
查看完整描述

1 回答

?
米脂

TA貢獻1836條經驗 獲得超3個贊

得到了解決方案

products := []*model.Product{}
DB.Preload("Categories").Find(&products)

這將返回所有產品及其類別。


查看完整回答
反對 回復 2023-07-31
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號