logo Buffalo slack logo
One to one associations
Database

One to Many Associations

In this chapter, you’ll learn how to write a one to one association in Pop.

Tags

One to one associations work using a pair of tags:

  • belongs_to for the model with the foreign key.
  • has_one for the model without the foreign key.

Example

// Models

type Head struct {
  ID           int
  BodyID       int        `db:"body_id"`
  Body         *Body      `belongs_to:"body"`
}

type Body struct {
  ID           int
  Head         Head       `has_one:"head"`
}
// Eager creation:
// Create a body with its head.
b := &models.Body{
    Head: models.Head{},
}

if err := tx.Eager().Create(b); err != nil {
    return err
}
// Eager fetch all bodies with their head.
bodies = &models.Bodies{}

if err := c.Eager().All(bodies); err != nil {
    log.Printf("err: %v", err)
    return
}

log.Printf("eager fetch: %v", bodies)