最初的想法是从 yii 构建 rbac 模拟https://github.com/yiisoft/yii2/blob/master/framework/rbac/migrations/schema-pgsql.sql
所以,我有这两个模型:
type AuthItem struct {
ID uint `gorm:"uniqueIndex;primaryKey;auto_increment;column:id" json:"id"`
Name string `gorm:"uniqueIndex;primaryKey;not null;type:varchar(64);column:name" json:"name"`
ItemType int64 `gorm:"type:smallint;not null;column:item_type" json:"item_type"`
Description string `gorm:"size:255;column:description" json:"description"`
}
type AuthRelations struct {
gorm.Model
Parent AuthItem `gorm:"references:id;foreignKey:parent;column:parent" json:"parent"`
Child AuthItem `gorm:"references:id;foreignKey:child;column:child" json:"child"`
}
我也已经在 auth_items 表中有一些数据,我想用 GORM 插入到 auth_relations 表中,它看起来像这样:
var relation = models.AuthRelations{
Parent: models.AuthItem{ID: 1},
Child: models.AuthItem{ID: 2},
}
err = db.Save(&relation).Error
if err != nil {
log.Fatalf("cant insert: %v", err)
}
我收到此错误:
failed to set value 0x1 to field Parent; failed to set value 0x1 to field Parent
我尝试使用 gorm 函数 Value(),类似于:
func (item AuthItem) Value() (driver.Value, error) {
return int64(item.ID), nil
}
在我实现这个功能后 db.Save 工作,但约束/外键/引用停止工作
所以我的问题是:是否有任何选项可以以正确的方式建立这样的关系,或者我如何在不失去约束的情况下使用 value() 函数?
胡说叔叔
拉丁的传说