我正在使用Sequelize,并且有以下代码:
迁移文件:
'use strict'
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('equipments', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
hostname: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
vendor: {
type: Sequelize.STRING,
allowNull: false
},
model: {
type: Sequelize.STRING,
allowNull: false
},
equipment_class_id: {
type: Sequelize.INTEGER,
allowNUll: false,
references: { model: 'equipment_classes' }
},
created_at: {
type: Sequelize.DATE,
allowNull: false
},
updated_at: {
type: Sequelize.DATE,
allowNull: false
}
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('equipments')
}
}
模型设备:
const { Model, DataTypes } = require('sequelize')
class Equipment extends Model {
static init (sequelize) {
super.init({
hostname: DataTypes.STRING,
vendor: DataTypes.STRING,
model: DataTypes.STRING,
equipmentClassId: {
type: DataTypes.INTEGER,
field: 'equipment_class_id'
}
}, {
sequelize
})
}
}
module.exports = Equipment
在数据库中,该表被创建为设备名称。
CREATE TABLE public.equipments
(
id integer NOT NULL DEFAULT nextval('equipments_id_seq'::regclass),
hostname character varying(255) COLLATE pg_catalog."default" NOT NULL,
vendor character varying(255) COLLATE pg_catalog."default" NOT NULL,
model character varying(255) COLLATE pg_catalog."default" NOT NULL,
equipment_class_id integer,
created_at timestamp with time zone NOT NULL,
updated_at timestamp with time zone NOT NULL,
CONSTRAINT equipments_pkey PRIMARY KEY (id),
CONSTRAINT equipments_hostname_key UNIQUE (hostname)
,
CONSTRAINT equipments_equipment_class_id_fkey FOREIGN KEY (equipment_class_id)
REFERENCES public.equipment_classes (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
当我运行此代码时:
async index (req, res) {
const equipments = await Equipment.findAll()
return res.json(equipments)
}
我收到错误:
Executing (default): SELECT "id", "hostname", "vendor", "model", "equipment_class_id" AS "equipmentClassId", "created_at" AS "createdAt", "updated_at" AS "updatedAt" FROM "equipment" AS "Equipment";
(node:17032) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: relation "equipment" does not exist
我的数据库:Postgresql 12
我还有其他类似创建的表,但是我没有这个问题,我在做什么错了?
Paulo
答案 0 :(得分:1)
您的问题正在命名。 Sequelize使用模型的名称自动重写到数据库表中。
在迁移中,您具有:
return queryInterface.createTable('equipments'...
但是您的模型具有:
class Equipment extends Model {
命名约定将模型中的名称复数以在数据库中查找。因此,您应该在迁移文件中添加
: return queryInterface.createTable('Equipment'...
设备是单数设备的复数形式。
您还可以使用sequelize-cli
简化此过程。
使用sequelize-cli
,您不必担心命名约定。只需运行(用您的属性列表替换属性列表):
sequelize model:generate --name Equipment --attributes fun:string,done:integer
它应该为您处理复数形式,生成一个迁移和模型文件。