Golang外键无法创建的解决方法
Golang外键无法创建的解决方法 外键未被创建…
type User struct{
gorm.Model
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
}
type Restaurant struct {
gorm.Model
Name string `json:"name"`
UserID uint `json:"ownerId"`
User User
}
// 在 psql 中创建表的函数...
db.CreateTable(&models.User{},&models.Restaurant{})
但是在 psql shell 中查看 \dt restaurants 或 \dt users 时,表仍然没有关联的外键…
更多关于Golang外键无法创建的解决方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于Golang外键无法创建的解决方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Golang中使用GORM时,外键未被创建通常是因为缺少明确的关联定义。以下是修正后的代码示例:
type User struct {
gorm.Model
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
// 添加反向关联(可选但推荐)
Restaurants []Restaurant `gorm:"foreignKey:UserID"`
}
type Restaurant struct {
gorm.Model
Name string `json:"name"`
UserID uint `json:"ownerId"`
// 明确指定外键关联
User User `gorm:"foreignKey:UserID;references:ID"`
}
或者使用标签明确指定约束:
type Restaurant struct {
gorm.Model
Name string `json:"name"`
UserID uint `json:"ownerId"`
User User `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;foreignKey:UserID"`
}
创建表时使用AutoMigrate:
db.AutoMigrate(&models.User{}, &models.Restaurant{})
对于PostgreSQL,还需要确保数据库用户有创建外键的权限:
-- 检查权限
SELECT grantee, privilege_type
FROM information_schema.role_table_grants
WHERE table_name = 'restaurants';
如果仍然有问题,可以手动添加外键:
// 迁移后手动执行SQL
db.Exec(`
ALTER TABLE restaurants
ADD CONSTRAINT fk_restaurants_user
FOREIGN KEY (user_id)
REFERENCES users(id)
ON DELETE SET NULL
`)
检查GORM日志确认SQL语句:
db.Debug().AutoMigrate(&models.User{}, &models.Restaurant{})
这将输出实际执行的SQL语句,帮助诊断问题。

