问题描述
我正在尝试用go实现一个小的状态机,并将状态存储在postgres数据库中。
我这样创建我的数据库:
CREATE TABLE state_machines
(
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),initial_state TEXT NOT NULL,"name" TEXT NOT NULL
);
CREATE TABLE state_machine_states
(
state_machine_id uuid NOT NULL REFERENCES state_machines(id) ON DELETE CASCADE,"name" TEXT NOT NULL,PRIMARY KEY(state_machine_id,"name")
);
// StateMachine is the DB schema
type StateMachine struct {
ID *uuid.UUID `pg:"id,pk,type:uuid,default:uuid_generate_v4()"`
Name string `pg:"name"`
InitialState string `pg:"initial_state"`
States []*StateMachinestate `pg:"fk:state_machine_id"`
}
// StateMachinestate is the DB schema
type StateMachinestate struct {
StateMachineID uuid.UUID `pg:"state_machine_id,fk"`
Name string `pg:"name"`
}
我正在使用go-pg 9.2,并且试图从“状态”关系中加载状态机及其状态列表。
我加载状态机的功能如下:
func (cep *repository) GetStateMachines() ([]*StateMachine,error) {
stateMachines := []*StateMachine{}
err := cep.db.Model(&stateMachines).
Relation("States").
Relation("Transitions").
Select()
return stateMachines,err
}
如果执行它,我总是收到错误消息Error reading state machine: model=StateMachine does not have relation="States"
我以前做过类似的关系,而且他们一直在工作,现在,我再也无法恢复工作了:(
解决方法
尝试升级到完全支持以下关系的v10:https://pg.uptrace.dev/orm/has-many-relation/
,查看go-pg中是否存在用于查询的.Debug()函数。 我使用https://gorm.io/,并且有一个Debug函数,它返回所有SQL查询。 当我看到要发送的查询时,我登录PostgreSQL并手动尝试以查看更详细的错误。