Belongs To

Belongs To

A belongs to association sets up a one-to-one connection with another model, such that each instance of the declaring model “belongs to” one instance of the other model.

For example, if your application includes users and profiles, and each profile can be assigned to exactly one user

type User struct {
gorm.Model
Name string
}

// `Profile` belongs to `User`, `UserID` is the foreign key
type Profile struct {
gorm.Model
UserID uint
User User
Name string
}

Foreign Key

To define a belongs to relationship, the foreign key must exists, default foreign key uses owner’s type name plus its primary key.

For the above example, to define a model that belongs to User, the foreign key should be UserID.

GORM provides a way to customize the foreign key, for example:

type User struct {
gorm.Model
Name string
}

type Profile struct {
gorm.Model
Name string
User User `gorm:"foreignkey:UserRefer"` // use UserRefer as foreign key
UserRefer uint
}

Association ForeignKey

For a belongs to relationship, GORM usually uses the owner’s primary key as the foreign key’s value, for above example, it is User‘s ID.

When you assign a profile to a user, GORM will save user’s ID into profile’s UserID field.

You are able to change it with tag association_foreignkey, e.g:

type User struct {
gorm.Model
Refer string
Name string
}

type Profile struct {
gorm.Model
Name string
User User `gorm:"association_foreignkey:Refer"` // use Refer as association foreign key
UserRefer string
}

Working with Belongs To

You could find belongs to associations with Related

db.Model(&user).Related(&profile)
//// SELECT * FROM profiles WHERE user_id = 111; // 111 is user's ID

For advanced usage, refer Association Mode