在gorm中如何使用预加载(preload)和联接表中的条件进行多对多关联查询?

huangapple go评论119阅读模式
英文:

How to preload in gorm many to many with the condition in join table

问题

这是翻译好的内容:

我又来了...
现在对我来说有一个大问题,但我很难思考它
现在我可以在gorm中预加载。但是当在多对多表中使用预加载和连接表时...我遇到了一些我不知道的问题
我有3个表

type Product struct{
Categories []Category `gorm:"many2many:Product_Category"`
}
type Category struct{}
type Product_Category struct {}

类似这样的。我现在可以使用Preload("Categories").Find(&products)
但问题在于如何通过类别筛选产品?
也就是说,我需要在预加载类别时在连接表Product_Category中添加条件吗?有没有解决方案?

此外,我想知道如何将带有类别的产品添加/更新到Product和Product_Category这两个表中?

英文:

It's me again...
Now the big issues for me but I hard to think about it
Now I can preload in gorm. But when using preload for many to many table with the join table... I have some issues that I dont know
I have 3 table

type Product struct{
Categories []Category `gorm:"many2many:Product_Category"`
}
type Category struct{}
type Product_Category struct {}

some kind like that. I now can using Preload("Categories").Find(&products)
But the problem here is how can I filter the product with category?
Mean I need to add the condition in the join table Product_Category when preload the category? Are there any solutions?

And beside that, I wonder how to add/update the product with categories into 2 table Product and Product_Category?

答案1

得分: 3

这段代码的意思是:

  • 创建一个多对多的关系,其中一个模型的外键是ID,引用为"product_id",另一个模型类似。
  • 然后,你只需要简单地预加载Categories。
英文:
type Product struct{
Product
Categories []Category `gorm:"many2many:product_category;foreignKey:ID;joinForeignKey:ProductID;References:ID;joinReferences:CategoryID"`
}
type Category struct{}
type Product_Category struct {}

This says

  • Create a many 2 many relationship with 1 foreign key being id of one model with reference as "product_id" and similar for other.
  • then all you need to do is simply preload Categories

huangapple
  • 本文由 发表于 2021年5月19日 21:46:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/67604535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定