我在Go中使用MySQL
数据库和GORM库。
添加或删除表以及插入行时,我没有任何问题。但是,foreignkey
不会发生,查询不会给出我想要的输出。
我正在从foreignkey
设计器窗口中观察Phpmyadmin
。
我在哪里想念?你能帮我吗?
进口:
"github.com/jinzhu/gorm"
_ "github.com/go-sql-driver/mysql"
实体:
type User struct {
gorm.Model
Username string `gorm:"type:varchar(255);"`
Password string `gorm:"type:varchar(255);"`
}
type Car struct {
gorm.Model
Engine string `gorm:"type:varchar(255);"`
Fuel string `gorm:"type:varchar(255);"`
}
type Garage struct {
gorm.Model
UserId uint `gorm:"not null; column:user_id;"`
CarId uint `gorm:"not null; column:car_id;"`
Colour string `gorm:"type:varchar(255);"`
User User
Car []Car `gorm:"foreignkey:ID"`
}
main()
user1 := User{Username: "foo", Password: "123"}
user2 := User{Username: "boo", Password: "123"}
user3 := User{Username: "qwe", Password: "123"}
car1 := Car{Engine: "V8", Fuel: "Gas"}
car2 := Car{Engine: "V12", Fuel: "Gas"}
car3 := Car{Engine: "V6", Fuel: "Diesel"}
garage1 := Garage{UserId: 1, CarId: 1, Colour: "red"}
garage4 := Garage{UserId: 1, CarId: 2, Colour: "black"}
garage2 := Garage{UserId: 2, CarId: 2, Colour: "blue"}
garage3 := Garage{UserId: 3, CarId: 3, Colour: "grey"}
db, err := gorm.Open("mysql", "root:root@/demo?charset=utf8&parseTime=True")
defer db.Close()
if err == nil {
fmt.Println("Nice!")
} else {
fmt.Println(err)
}
db.SingularTable(true)
db.DropTableIfExists(Garage{})
db.DropTableIfExists(User{})
db.DropTableIfExists(Car{})
db.CreateTable(User{})
db.CreateTable(Car{})
db.CreateTable(Garage{})
db.Create(&user1)
db.Create(&user2)
db.Create(&user3)
db.Create(&car1)
db.Create(&car2)
db.Create(&car3)
db.Create(&garage1)
db.Create(&garage2)
db.Create(&garage3)
db.Create(&garage4)
ggg := Garage{}
db.Where("user_id = ?", "1").Preload("User").Preload("Car").Find(&ggg)
for _, item := range ggg.Car{
fmt.Println(item.Engine)
}
输出:
Nice!
Process finished with exit code 0
编辑1:
我认为通过标记,外键的添加是不同的。 它是这样添加的:
db.Table("garage").AddForeignKey("user_id","user(id)","CASCADE","CASCADE")
db.Table("garage").AddForeignKey("car_id","car(id)","CASCADE","CASCADE")
但是,我仍然无法与数据库建立一对多关系。有什么建议吗?