Open pejman-hkh opened 7 months ago
Your current error is not a bug with the gorm framework, but a basic program compilation error. When the object is initialized, it will cause a cross-pointer reference, but the referenced object is not fully initialized, so it will cause infinite recursion.
If you want to correlate the two, consider referencing the array of the other struct in the current struct
type User struct {
BaseModel
UserID uint gorm:"index"
GroupID uint gorm:"index"
Groups []Group json:"groups"
}
type Group struct {
BaseModel
UserId uint gorm:"index"
Users []User json:"users"
}
The sample you can refer to : https://github.com/go-gorm/gorm/issues/6943#issuecomment-2053661459
I know that is compilation error. in my case User model is belong to Group and Group model is belong to User and I don't have array and your answer is not the solution.
Groups[0] is Groups
Let me check it
It returns empty array
I also set preload Preload("Users")
please give me code sample, I'm at work right now and don't have much time to solve your problem, I will response you later 😅
thank you a lot for your response and happy for you that have a job :D my project link:
https://github.com/pejman-hkh/gorn/blob/main/api/app/model/group.go
checkout this: https://github.com/pejman-hkh/gorn/pull/1
Let me describe better my problem.
My group has a user creator that created it or I have a User that another user created it, How can get this User in belong to and preload
. I don't need users of one group ! I just want user that is belong to userid
column on same table.
I solved this problem with made another package name with same model name with required fields. with helper model I can fetch each fields that I require.
If Gorm
let us to define Table Name
in struct we can fetch each fields we require with define struct on same place :
type Group struct {
Title string `gorm:"size:255" json:"title"`
UserId uint `gorm:"index" json:"user_id"`
User struct {
Table string `gorm:"table:users"`
ID uint
Name string
}
}
@jinzhu you can close this issues
Your Question
Consider we have a Group model, and Group model has
UserId
and User model hasGroupId
andUserId
too. How can I set User Belong to Group ?I go below error in golang compilation:
invalid recursive type Group
The document you expected this should be explained
Expected answer