如何使用 Gorm 将外键添加到模型
How to add Foreign Key to a model using Gorm
我正在尝试使用 gorm 向模型添加外键。我应该如何将 User
模型的对象作为外键传递给 Profile
模型?
我的main.go
:
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type User struct {
gorm.Model
Refer string
Name string
}
type Profile struct {
gorm.Model
Name string
User User `gorm:"association_foreignkey:Refer"` // use Refer as association foreign key
UserRefer string
}
func main() {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
// Migrate the schema
db.AutoMigrate(&User{})
db.AutoMigrate(&Profile{})
// Create
db.Create(&User{Name: "Clifton"})
// Read
var user User
db.Debug().First(&user, 1)
db.Debug().Create(&Profile{Name: "Clifton",
UserRefer: "yyyyy"}).Association("User").Append(user)
// db.Debug().Model(&user).Association("Refer").Append(user)
var profile Profile
db.Debug().Find(&profile, 1)
fmt.Println(profile.Name, profile.UserRefer, profile.User.ID, profile.User.CreatedAt)
}
问题的代码将创建 user(id=1)
和 profile(id = 1)
之间的关联
您还可以使用 Association 附加外键值。
var user User
db.First(&user, 1)
db.Model(&user).Association("Refer").Append(user)
我正在尝试使用 gorm 向模型添加外键。我应该如何将 User
模型的对象作为外键传递给 Profile
模型?
我的main.go
:
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type User struct {
gorm.Model
Refer string
Name string
}
type Profile struct {
gorm.Model
Name string
User User `gorm:"association_foreignkey:Refer"` // use Refer as association foreign key
UserRefer string
}
func main() {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
// Migrate the schema
db.AutoMigrate(&User{})
db.AutoMigrate(&Profile{})
// Create
db.Create(&User{Name: "Clifton"})
// Read
var user User
db.Debug().First(&user, 1)
db.Debug().Create(&Profile{Name: "Clifton",
UserRefer: "yyyyy"}).Association("User").Append(user)
// db.Debug().Model(&user).Association("Refer").Append(user)
var profile Profile
db.Debug().Find(&profile, 1)
fmt.Println(profile.Name, profile.UserRefer, profile.User.ID, profile.User.CreatedAt)
}
问题的代码将创建 user(id=1)
和 profile(id = 1)
您还可以使用 Association 附加外键值。
var user User
db.First(&user, 1)
db.Model(&user).Association("Refer").Append(user)