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 { |
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) |
For lazy load call relation method and get
DB.Model(&u1).Find(&lazy, u2.Id) |
Inverse of HasMany Belongs To
Define relation
type Post struct { |
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 |
For lazy load call relation method and get it
var lazy Post |