-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Customized Join Table Select/Update #4051
Comments
Preload won't query join table's content, use the join table as has-many to load its value.
When using many2many, GORM will only create the record with |
@jinzhu Regarding the point package main
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type User struct {
ID uint
Name string
}
type ProjectUser struct {
UserID uint
ProjectID uint
Roles string
}
func (user *ProjectUser) BeforeSave(db *gorm.DB) error {
user.Roles = "default_val"
return nil
}
type Project struct {
ID uint
Name string
Users []User `gorm:"many2many:project_users;"`
}
func main() {
db, err := gorm.Open(sqlite.Open("test4.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&User{}, &Project{})
if err := db.SetupJoinTable(&Project{}, "Users", &ProjectUser{}); err != nil {
println(err.Error())
panic("Failed to setup join table")
}
bogdan := User { Name: "Bogdan" }
db.Create(&bogdan)
db.Create(&Project{Name: "Test1", Users: []User {{ID: bogdan.ID}}})
}
|
@BogdanJava same is happening with me. @jinzhu what can be the issue? |
@BogdanJava I've figured it out. Add the |
Yes it worked for me, nice solution. Thanks for the help. |
@BogdanJava @shreeyashnaik Something I still don't understand... In @BogdanJava's example above, how does one populate the |
yea same here, can you provide example, specially on the official documentation, i was even surprised in the first place not finding it |
Your Question
Say for example I have these structs:
My question is:
a) how do I select these custom field out of the join table to get them as JSON when selecting out Person with Preload of Addresses
b) how do I save new values to these, the documentation says you can have custom fields but doesn't explain how to actually do this
The document you expected this should be explained
https://gorm.io/docs/many_to_many.html#Customize-JoinTable
Expected answer
Documentation describing how this could be done?
The text was updated successfully, but these errors were encountered: