Getting Started
Request handling
- Routing
- Action Controller
- Resources
- Context
- Request Binding
- Middleware
- Error Handling
- Sessions
- Cookies
Frontend
Database
- Getting started with Pop
- Soda CLI
- Database Configuration
- Buffalo Integration
- Models
- Generators
- Migrations
- Fizz
- Mutations
- Querying
- Raw Queries
- Callbacks
- Scoping
- Associations and Relationships
- One to one associations
- One to many associations
Guides
- API Applications
- File Uploads
- Background Job Workers
- Mailers
- Tasks
- Plugins
- Local Authentication
- Third Party Authentication
- Events
- Go Modules
- Localization
- Logging
- Template Engines
- Testing
- Videos
Deploy
One to one associations
Database
One to One 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)
Related Content
- Associations with Pop: 1 to 1 - An article about 1 to 1 associations in Pop.