Updating Multiple Records
Updating multiple records can be very similar to updating single records. In updating a single record you have to use the Where
function to narrow down your record set. Here, you may need to use that, or you may need to use the All
function as below. Since using the Where
function has been demonstrated we'll show the All
function.
package main
import (
"bitbucket.org/pop-book/models"
"fmt"
"github.com/gobuffalo/pop"
"log"
)
func main() {
tx, err := pop.Connect("development")
if err != nil {
log.Panic(err)
}
users := []models.User{}
err = tx.All(&users)
if err != nil {
fmt.Print("ERROR!\n")
fmt.Printf("%v\n", err)
} else {
for i := 0; i < len(users); i++ {
user := users[i]
user.Location = "NYC, NY"
tx.ValidateAndSave(&user)
fmt.Print("Success!\n")
fmt.Printf("%v\n", user)
}
}
}
Compile and run:
$ ./main
Success!
{"id":"bf3ba75b-8dfe-4619-b832-31c4a087a589","created_at":"2017-12-19T14:06:20.473953-05:00","updated_at":"2017-12-28T21:50:00.094151-05:00","title":"Ms.","first_name":"Jessica","last_name":"Jones","bio":"Private security, super hero.","location":"NYC, NY"}
Success!
{"id":"61b2db41-a66b-4093-8580-be0b114ec04e","created_at":"2017-12-19T14:06:20.476127-05:00","updated_at":"2017-12-28T21:50:00.096033-05:00","title":"Mr.","first_name":"Luke","last_name":"Cage","bio":"Hero for hire.","location":"NYC, NY"}
Success!
{"id":"d86df65e-2bf8-4bec-9b23-8d7b274a401a","created_at":"2017-12-19T14:06:20.476837-05:00","updated_at":"2017-12-28T21:50:00.096708-05:00","title":"Mr.","first_name":"Danny","last_name":"Rand","bio":"Martial artist.","location":"NYC, NY"}
Success!
{"id":"bd73c1a3-0259-4e0a-a3b2-232cf94b52ff","created_at":"2017-12-19T14:06:20.47763-05:00","updated_at":"2017-12-28T21:50:00.097364-05:00","title":"Mr.","first_name":"Matthew","last_name":"Murdock","bio":"Lawyer, sees with no eyes.","location":"NYC, NY"}
Success!
{"id":"240ec3c5-019d-4031-9c27-8a553e022297","created_at":"2017-12-19T14:06:20.478384-05:00","updated_at":"2017-12-28T21:50:00.098018-05:00","title":"Mr.","first_name":"Frank","last_name":"Castle","bio":"USMC, badass.","location":"NYC, NY"}