Your Question

我希望我的外键值为 NUll,但是 GORM 却将它设置为 0

// District 行政区域
// 数据来源 https://github.com/uiwjs/province-city-china
type District struct {
    ID       uint        `json:"id"   gorm:"primarykey"`                   // 地区ID
    PID      uint        `json:"pid"  gorm:"column:pid;default:null"`      //
    Code     string      `json:"code" gorm:"unique"`                       // 地址代码
    Name     string      `json:"name"`                                     // 地区名字
    Level    uint        `json:"level"`                                    // 地区等级,省1 市2 县3
    Children []*District `json:"children,omitempty" gorm:"foreignkey:PID"` //
}

Gorm 如何使外键值为 NULL?

上图红色框内的值应该为 NUll,不然在 MySQL 的 InnoDB 引擎下 AutoMigrateSave 方法无法正常工作,会触发下面的错误:

Error 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`shopfix`.`#sql-1e858_11`, CONSTRAINT `fk_erp_districts_children` FOREIGN KEY (`pid`) REFERENCES `erp_districts` (`id`))

The document you expected this should be explained

Expected answer

Comment From: a631807682

func TestGORM(t *testing.T) {
    DB.Migrator().DropTable(&District{})
    DB.AutoMigrate(&District{})

    d1 := District{Name: "d1", Code: "d1", Children: []*District{
        {Name: "d2", Code: "d2"},
        {Name: "d3", Code: "d3"},
    }}
    DB.Create(&d1)
}

Did not reproduce on the latest version, it seems to be a problem with your definition REFERENCES erp_districts (id)

Comment From: tint

应该是我初始化出了问题