想生成的表如下:
CREATE TABLE `blogs` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`blog_type_id` int unsigned DEFAULT NULL,
`user_id` int unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `title` (`user_id`,`blog_type_id`),
KEY `idx_blogs_deleted_at` (`deleted_at`),
KEY `blogs_blog_type_id_blog_types_id_foreign` (`blog_type_id`),
CONSTRAINT `blogs_blog_type_id_blog_types_id_foreign` FOREIGN KEY (`blog_type_id`) REFERENCES `blog_types` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT `blogs_user_id_users_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
根据官方示例:
type User struct {
gorm.Model
CreditCards []CreditCard
}
type CreditCard struct {
gorm.Model
Number string
UserID uint
}
models设计如下:
// Blog blog模型
type Blog struct {
gorm.Model
BlogTypeID uint `json:"type_id" binding:"required"`
UserID uint `json:"user_id"`
}
// User user模型
type User struct {
gorm.Model
Username string `json:"username" form:"username" binding:"required" gorm:"type:varchar(20);not null;unique"`
Blogs []Blog
}
// BlogType blog_type模型
type BlogType struct {
ID uint `json:"id" gorm:"primary_key"`
Type string `json:"type" binding:"required" gorm:"not null;unique"`
Blogs []Blog
}
自动迁移后生成的表并没有外键:
CREATE TABLE `blogs` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`blog_type_id` int unsigned DEFAULT NULL,
`user_id` int unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `title` (`user_id`,`blog_type_id`),
KEY `idx_blogs_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
只能用db.Models().AddForeignKey().AddForeignKey() 才能添加外键,但我只想用models自动迁移。。。
请问如何设计模型才能添加这两个外键?
|