has many 与另一个模型建立一对多的连接,不同于has one,拥有者可以有零或多个关联模型。
连接数据库
package main
import("gorm.io/driver/mysql""gorm.io/gorm")var db *gorm.DB
funcinit(){
dsn :="root:123456@tcp(127.0.0.1:3306)/golang_test?charset=utf8mb4&parseTime=True&loc=Local"
d, err := gorm.Open(mysql.Open(dsn),&gorm.Config{})if err !=nil{panic("failed to connect database")}
db = d
}
User有多张CreditCard, UserID是外键
type User struct{
gorm.Model
Name string
CreditCards []CreditCard
}type CreditCard struct{
gorm.Model
Number string
UserID uint}