1 回答
TA贡献1874条经验 获得超12个赞
在阅读了文档和一堆 StackOverflow 答案后,对我来说没什么用。文档和/或 StackOverflow 建议我在迁移模型时添加约束,或/并将约束添加到 structs gorm:"constraint:OnDelete:CASCADE;"
,我也尝试db.Select("cars").Delete(&customers)
过但没有成功。这就是我的做法,不确定这是否是最佳做法,但它会从数据库中删除其相关记录。我像这样更新了 deleteCustomer 和 deleteCar 端点:
//delete customer
func deleteCustomer(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
setupResponse(&w, r)
if (*r).Method == "OPTIONS" {
return
}
var customer Customer
var cars []Car
db.First(&customer, params["id"])
db.Model(&customer).Related(&cars)
deleteServicesSqlStatement := `
DELETE FROM services
WHERE car_id = $1;`
for i, car := range cars {
fmt.Println(i, car.ID)
err := db.Exec(deleteServicesSqlStatement, car.ID).Error
if err != nil {
fmt.Println(err)
}
}
DeleteCarsSqlStatement := `
DELETE FROM cars
WHERE customer_id = $1;`
err := db.Exec(DeleteCarsSqlStatement, params["id"]).Error
if err != nil {
fmt.Println(err)
}
db.Debug().Unscoped().Delete(&customer)
json.NewEncoder(w).Encode(&customer)
}
//delete car
func deleteCar(w http.ResponseWriter, r *http.Request) {
//handle CORS
setupResponse(&w, r)
if (*r).Method == "OPTIONS" {
return
}
params := mux.Vars(r)
var car Car
db.First(&car, params["id"])
sqlStatement := `
DELETE FROM services
WHERE car_id = $1;`
err := db.Exec(sqlStatement, params["id"]).Error
if err != nil {
fmt.Println(err)
}
db.Debug().Unscoped().Delete(&car)
json.NewEncoder(w).Encode(&car)
}
- 1 回答
- 0 关注
- 77 浏览
添加回答
举报