A User and Company are defined. Users can contain multiple companies, as follows:
type User struct { ID int `gorm:"TYPE:int(11);NOT NULL;PRIMARY_KEY;INDEX"` Name string `gorm:"TYPE: VARCHAR(255); DEFAULT:'';INDEX"` Companies []Company `gorm:"FOREIGNKEY:UserId;ASSOCIATION_FOREIGNKEY:ID"` CreatedAt time.Time `gorm:"TYPE:DATETIME"` UpdatedAt time.Time `gorm:"TYPE:DATETIME"` DeletedAt *time.Time `gorm:"TYPE:DATETIME;DEFAULT:NULL"` } type Company struct { gorm.Model Industry int `gorm:"TYPE:INT(11);DEFAULT:0"` Name string `gorm:"TYPE:VARCHAR(255);DEFAULT:'';INDEX"` Job string `gorm:"TYPE:VARCHAR(255);DEFAULT:''"` UserId int `gorm:"TYPE:int(11);NOT NULL;INDEX"` }
When querying User, you want to query Company information together. There are three methods:
Related
Using the Related method, you need to query the User, and then find the Company according to the FOREIGNKEY specified in the User definition. If it is not defined, you need to specify it when calling, as follows:
var u User db.First(&u) db.Model(&u).Related(&u.Companies).Find(&u.Companies)
Traversing the list when User list queries Company one by one
Association
To use the Association method, you need to query the User, and then find the Company according to the AssociationForeignKey specified in the User definition, which must be defined as follows:
var u User db.First(&u) db.Model(&u).Association("Companies").Find(&u.Companies)
Preload
Using the Preload method, when querying the User, first obtain the Company record, as follows:
// Query single user var u User db.Debug().Preload("Companies").First(&u) // Corresponding sql statement // SELECT * FROM users LIMIT 1; // SELECT * FROM companies WHERE user_id IN (1); // Query all user s var list []User db.Debug().Preload("Companies").Find(&list) // Corresponding sql statement // SELECT * FROM users; // SELECT * FROM companies WHERE user_id IN (1,2,3...);
In this paper, one to many and one to one are similar. For the complete code, see: GORM Related