Let’s say we have a User model,every User has an Address, it’s a one-to-one relation . Table address has column user_id correspond to user table id column. For User model,we add goelo:"HasOne:AddressRelation" tag to User‘s Address filed.
Model definition
type UserT struct { *goeloquent.EloquentModel Id int64`goelo:"column:id;primaryKey"` UserName string`goelo:"column:name"` Age int`goelo:"column:age"` ViewedPosts []Post `goelo:"BelongsToMany:ViewedPostsRelation"` Friends []UserT `goelo:"BelongsToMany:FriendsRelation"` Address Address `goelo:"HasOne:AddressRelation"` Posts []Post `goelo:"HasMany:PostsRelation"` Roels []Role `goelo:"HasMany:RelesRelation"`
type Address struct { *goeloquent.EloquentModel ID int64`goelo:"column:id;primaryKey"` UserT *UserT `goelo:"BelongsTo:UserRelation"` UserId int64`goelo:"column:user_id"` Country string`goelo:"column:country"` State string`goelo:"column:state"` City string`goelo:"column:city"` Detail string`goelo:"column:detail"` }
HasOne first param is always the current model pointer, in this case it’s a user pointer,second one is the pointer of the related model(address), third one is the self model key ,user id that correspond to the address user_id ,the fourth one is the address key that correspond to the users’ id key
Get relations
Use With to eager load
var uu1 UserT var us []UserT DB.Model(&uu1).With("Address").Find(&uu1, u1.Id) DB.Model(&UserT{}).With("Address").WhereIn("id", []int64{u2.Id, u4.Id}).Get(&us)