go - 我怎样才能在 golang gorm 中与 self 建立多对多的关系?

标签 go psql go-gorm

我有一个 psql 数据库,我正在使用 gorm 库和 pq 驱动程序,如您所见,相关产品存在多对多关系,但这会抛出错误 pq: column "product_id"指定了不止一次 有没有办法设置别名,或者我是否以错误的方式解决这个问题?

type Product struct {
    Id          int64      `json:"_id"`
    Price       float32    `json:"price"`
    Name        string     `sql:"size:255" json:"name"`
    Description string     `json:"description"`
    Material    string     `json:"material"`
    Color       string     `json:"color"`
    ColorId     int64      `json:"colorId"`
    Categories  []Category `gorm:"many2many:product_categories;" json:"categories"`
    Images      []Image    `json:"images"`
    Tags        []Tag      `gorm:"many2many:product_tags;" json:"tags"`
    Main        bool       `json:"main"`
    Available   bool       `json:"available"`
    Slug        string     `json:"slug"`
    CreatedAt   time.Time  `json:"createdAt"`
    Related     []Product  `gorm:"many2many:related_products;" json:"related"`
}

最佳答案

我找到了自引用多对多关系的解决方案。 :D

type User struct {
    Id int64
    Related     []Product  `gorm:"foreignkey:product_id;associationforeignkey:related_product_id;many2many:related_products;" json:"related"`        
}

关于go - 我怎样才能在 golang gorm 中与 self 建立多对多的关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27672876/

相关文章:

mysql - App Engine 中的 GoLang 动态 SQL 查询

go - 在 Go 中是否可以有一个指向带有参数的成员函数/方法的指针?

sql - 找到给定日期/时间戳最近的记录(之前或之后)

postgresql - 将 gorm.Model 字段集成到 protobuf 定义中

go - 数据库查询命令正在生成奇怪的 sql 查询

sql-server - 使用GORM连接到SQLServer

go - 通过锁请求时间同步获取锁

go - 如何处理以数组作为返回值的 go RPC 调用?

php - Digitalocean 远程 psql 数据库与本地 PDO (RedBean php) 脚本

grails - 查找时跳过锁定的GORM对象