Search code examples
gogo-gorm

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


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?


Solution

  • 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