I have 2 models with Gorm like below:
type Post struct {
*gorm.Model
ID uint32 `gorm: "primarykey"`
PostTitle string `gorm:"posttitle;not null"`
PostSlug string `gorm:"postslug;unique;not null"`
PostCategoryID uint32 `gorm:"postcategoryid"`
PostCollections []PostCollection `gorm:"many2many:post_collection;"`
PostTags []PostTag `gorm:"many2many:post_tag; constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}
type PostCategory struct {
ID uint32 `gorm: "primarykey"`
PostCatName string `gorm:"postcatname;not null"`
PostCatSlug string `gorm:"postcatslug;unique;not null"`
PostCatParent uint32 `gorm: "postcatparent"`
Posts []Post `gorm:"foreignKey:PostCategoryID"`
}
I want get all posts of a parent category (which has many child categories) with function like below:
func GetPostByCategory(c *fiber.Ctx) error {
db := database.DB //connect database
var post []models.Post
var categories []models.PostCategory
cat := c.Params("catslug") //get slug value of parent category from route
cate := GetCategoryChild(cat) //get array of child category
db.Model(&categories).Where("id IN (?)", cate).Association("Posts").Find(&post)
return c.JSON(post)
}
It return nil array . Please help me to fix this