One To Many Relation

One To Many

In this example a user has many posts, a post belongsto a author(user),so table post column author_id correspond
to user table id column

Model definition

type UserT struct {
*goeloquent.EloquentModel
Id int64 `goelo:"column:id;primaryKey"`
UserName string `goelo:"column:name"`
Age int `goelo:"column:age"`
Posts []Post `goelo:"HasMany:PostsRelation"`
CreatedAt time.Time `goelo:"column:created_at;CREATED_AT"`
UpdatedAt sql.NullTime `goelo:"column:updated_at;UPDATED_AT"`
}
func (u *UserT) PostsRelation() *goeloquent.RelationBuilder {
return u.HasMany(u, &Post{}, "id", "author_id")
}

HasMany takes 4 parameter,first one is a pointer of current model here is user,second is a pointer of related model(post), third is
related model database column correspond to current model,last one is current model field correspond to third
parameter.

Get relations

DB.Model(&u1).With("Posts").Find(&uu1, u1.Id)
DB.Model(&UserT{}).With("Posts").Get(&us)

For lazy load call relation method and get

DB.Model(&u1).Find(&lazy, u2.Id)
lazy.PostsRelation().Get(&lazyPosts)

Inverse of HasMany Belongs To

Define relation

type Post struct {
*goeloquent.EloquentModel
ID int64 `goelo:"column:pid;primaryKey"`
Title string `goelo:"column:title"`
Author UserT `goelo:"BelongsTo:AuthorRelation"`
AuthorId int64 `goelo:"column:author_id"`
}

func (p *Post) AuthorRelation() *goeloquent.RelationBuilder {
return p.BelongsTo(p, &UserT{}, "author_id", "id")
}

BelongsTo takes 4 parameter,first one is a pointer of current model(post),second is a pointer of related model(user), third is
current model database column correspond to related model,last one is related model column correspond to current model parameter.

Get relations

Use With to eager load

var pp1, pp4 Post
var ps []Post
DB.Model(&pp1).With("Author").Find(&pp1, p1.ID)
DB.Model(&Post{}).With("Author").WhereIn("pid", []int64{p2.ID, p3.ID}).Get(&ps)

For lazy load call relation method and get it

var lazy Post
var lazyUser UserT
DB.Model(&p1).Find(&lazy, p2.ID)
lazy.AuthorRelation().Get(&lazyUser)