One To One Relation

One To One

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"`

CreatedAt time.Time `goelo:"column:created_at;CREATED_AT"`
UpdatedAt sql.NullTime `goelo:"column:updated_at;UPDATED_AT"`
}

func (u *UserT) AddressRelation() *goeloquent.RelationBuilder {
rb := u.HasOne(u, &Address{}, "id", "user_id")
rb.EnableLogQuery()
return rb
}

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)

For lazy load call relation method and get it

DB.Model(&u1).Find(&lazy, u2.Id)
lazy.AddressRelation().Get(&lazyAddress)

Inverse of HasOne BelongsTo

Define relation

func (a *Address) UserRelation() *goeloquent.RelationBuilder {
rb := a.BelongsTo(a, &Address{}, "id", "user_id")
rb.EnableLogQuery()
return rb
}

Get relations

Use With to eager load

var a Address
var as []Address
DB.Model(&a).With("User").Find(&a, id)
DB.Model(&Address{}).With("User").WhereIn("id", []int64{id1, id2}).Get(&as)

For lazy load call relation method and get it

var lazyUser UserT
DB.Model(&a1).Find(&lazy, a2.Id)
lazy.UserRelation().Get(&lazyUser)