Gorm relationship error: need to define a valid foreign key for relations or it need to implement the Valuer/Scanner interface

在使用gorm创建关系模型时, 出现了这个错误, google了一下这个错误, 解决了问题

首先我之前的模型定义是:

type Ticket struct {
	ID              int `gorm:"primaryKey;autoIncrement;size:11"`
	Workflow        Workflow
	WorkflowID      int `gorm:"column:workflow_id"`
	WorkflowState   WorkflowState
	WorkflowStateID int         `gorm:"column:workflow_state"`
	Relation        string      `gorm:"size:1000"`
	User            Users       
	CreateUser      int         `gorm:"column:create_user"`
	Title           string      `gorm:"size:100"`
	Participant     string      `gorm:"size:1000"`
	ParticipantType int         `gorm:"column:participant_type"`
	ActState        int         `gorm:"act_state"`
	TicketInput     string      `gorm:"column:ticket_input"`
	CreateTime      FormartTime `gorm:"column:create_time"`
	UpdateTime      FormartTime `gorm:"column:update_time"`
	Description     string
}

在数据库中的表格结构是这样的

问题就出在User这个属性上, 我们需要改成

type Ticket struct {
	ID              int `gorm:"primaryKey;autoIncrement;size:11"`
	Workflow        Workflow
	WorkflowID      int `gorm:"column:workflow_id"`
	WorkflowState   WorkflowState
	WorkflowStateID int         `gorm:"column:workflow_state"`
	Relation        string      `gorm:"size:1000"`
	User            Users       `gorm:"foreignKey:CreateUser;references:ID"`
	CreateUser      int         `gorm:"column:create_user"`
	Title           string      `gorm:"size:100"`
	Participant     string      `gorm:"size:1000"`
	ParticipantType int         `gorm:"column:participant_type"`
	ActState        int         `gorm:"act_state"`
	TicketInput     string      `gorm:"column:ticket_input"`
	CreateTime      FormartTime `gorm:"column:create_time"`
	UpdateTime      FormartTime `gorm:"column:update_time"`
	Description     string
}

User Users `gorm:"foreignKey:CreateUser;references:ID"`

由于我们的外键不是默认的字段名, 所以需要用forignKey与references指定我们的外键关系


评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注