Deleting Multiple Records

Deleting multiple records can be very similar to deleting single records. In deleting a single record you have to use the Where function to narrow down your record set. Here, we'll use the Where function because we only want to remove two of the records.

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)
    }

    query := tx.Where("last_name = 'Rand' OR last_name = 'Murdock'")
    users := []models.User{}
    err = query.All(&users)
    if err != nil {
        fmt.Print("ERROR!\n")
        fmt.Printf("%v\n", err)
    } else {
        fmt.Print("Found users - now delete them.\n")
        fmt.Printf("%v\n", users)
        for i := 0; i < len(users); i++ {
            user := users[i]
            tx.Destroy(&user)
        }
    }
}

Compile and run:

$ ./main
Found users - now delete them.
[{"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"} {"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"}]

Now, as an alternative way, let's verify those records were removed.

sqlite> SELECT * FROM users;
bf3ba75b-8dfe-4619-b832-31c4a087a589|Mrs.|Jessica|Jones|Private security, super hero.|2017-12-19 14:06:20.473953-05:00|2017-12-28 21:57:45.771782-05:00|NYC, NY
61b2db41-a66b-4093-8580-be0b114ec04e|Mr.|Luke|Cage|Hero for hire.|2017-12-19 14:06:20.476127-05:00|2017-12-28 21:50:00.096033-05:00|NYC, NY

results matching ""

    No results matching ""