As of December 1st, 2019 Buffalo, and all related packages, require Go Modules and the use of the
GOPATH
is no longer supported.
Please see this blog post for more information https://blog.gobuffalo.io/the-road-to-1-0-requiring-modules-5672c6b015e5.
Mutations
In this chapter, you'll learn how to create, update and delete objects from you database using Pop.
Create
Without validation
c, err := pop.Connect("development")
// [...]
fruit := &models.Fruit{}
// Create a fruit without running validations
err := c.Create(fruit)
With validation
c, err := pop.Connect("development")
// [...]
fruit := &models.Fruit{}
// Run validations and create if all validations passed
vErrors, err := c.ValidateAndCreate(fruit)
Update
Without validation
c, err := pop.Connect("development")
// [...]
fruit := &models.Fruit{}
// Update a fruit without running validations
err := c.Update(fruit)
With validation
c, err := pop.Connect("development")
// [...]
fruit := &models.Fruit{}
// Run validations and update if all validations passed
vErrors, err := c.ValidateAndUpdate(fruit)
Save
Save checks for the ID in you model: if the ID is the zero value of the type (so for example if it's an int
and its value is 0
), Save
calls Create
.
Otherwise, it calls Update
.
Without validation
c, err := pop.Connect("development")
// [...]
fruit := &models.Fruit{ID: 0}
// Create a fruit without running validations
err := c.Save(fruit)
c, err := pop.Connect("development")
// [...]
fruit := &models.Fruit{ID: 1}
// Update a fruit without running validations
err := c.Save(fruit)
With validation
c, err := pop.Connect("development")
// [...]
fruit := &models.Fruit{ID: 0}
// Run validations and create if all validations passed
vErrors, err := c.ValidateAndSave(fruit)
c, err := pop.Connect("development")
// [...]
fruit := &models.Fruit{ID: 1}
// Run validations and update if all validations passed
vErrors, err := c.ValidateAndSave(fruit)
Delete
c, err := pop.Connect("development")
// [...]
fruit := &models.Fruit{ID: 1}
// Destroy the fruit
err := c.Destroy(fruit)
Next Steps
- Querying - Fetch the data you inserted in the database.
- Associations and Relationships - Handle relations between models.
Feedback
If you found an error or something which needs to be improved, and you want to contribute to fix it:
If you'd like to suggest something to improve this page: