My database structure goal
one user can join many communities
and
one user can own a community
This is the structure that I came up with, is this correct?
type User struct {
gorm.Model
Communities []Community `gorm:"many2many:user_communities" json:"communities"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
}
type Community struct {
gorm.Model
Name string `json:"name"`
UserID uint `json:"userID"`
Users []User `gorm:"many2many:user_communities" json:"users"`
}
This is my database setup
func ConnectMysql() {
// Connect to Mysql database based on the environment variable
dsn := os.Getenv("MYSQL_DSN")
database, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("Failed to connect to the database")
}
database.AutoMigrate(&models.User{})
database.AutoMigrate(&models.Community{})
DB = database
}
and how do I query to check whether a user belongs to a community?
So far I came up with this but it's not working, probably my schema above is wrong
func CreateQuestion() {
var community Community
var foundUser User
communityID = 1
userID = 1
// Find the community
if err := database.Mysql.Where("id = ?", communityID).First(&community).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Community does not exist"})
return
}
// Im not sure whether this query is to check whether the user belongs to the community with id 1 or not.
if err := database.Mysql.Preload("Community").Where("id = ?", userID).Find(&foundUser).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "user is not in the community"})
return
}
}
The error that I got
[error] invalid field found for struct github.com/testing-be/Community's field Users: define a valid foreign key for relations or implement the Valuer/Scanner interface