我正在尝试应该很简单的方法,但是没有互联网的帮助可以解决这个特定问题。
使用Sequelize,我对两个简单的数据库表进行了建模,以作为此处工作的概念证明。它们是下面的Person
和NaturalPerson
模型:
import { NaturalPerson } from './natural_person';
import Connection from './database/database.conn';
import { Model, DataTypes } from "sequelize";
export class Person extends Model {
static isNaturalPerson(id) {
return Person.findOne({
include: [{
model: NaturalPerson,
required: true
}],
where: { id: id }
});
}
}
Person.init({
'id': {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
'creation_date': {
type: DataTypes.DATEONLY,
allowNull: false
}
}, {
sequelize: Connection,
timestamps: false,
freezeTableName: true,
tableName: 'person',
modelName: 'Person'
});
Person.hasOne(NaturalPerson, { foreignKey: 'person_id' });
export default Person;
import { Person } from "./person";
import Connection from './database/database.conn';
import { Model, DataTypes } from "sequelize";
export class NaturalPerson extends Model { }
NaturalPerson.init({
'id': {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
'rg': {
type: DataTypes.TEXT,
allowNull: true
},
'cpf': {
type: DataTypes.CHAR(11),
allowNull: true
},
'name': {
type: DataTypes.STRING,
allowNull: false
},
'birth_date': {
type: DataTypes.DATEONLY,
allowNull: true
},
'person_id': {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'person',
key: 'id'
}
}
}, {
sequelize: Connection,
timestamps: false,
freezeTableName: true,
tableName: "natural_person"
});
NaturalPerson.belongsTo(Person, { foreignKey: 'person_id', targetKey: 'id' });
由于某种未知的原因,如果我注释掉NaturalPerson.belongsTo(Person, { foreignKey: 'person_id', targetKey: 'id' });
行,那么一切都很好,但取消注释会返回我
ReferenceError: Person is not defined
at Object.<anonymous> (<source code path>\natural_person.js:45:31)
我完全不知道问题可能出在哪里。即使我知道它是一个简单的未定义对象,也无法理解如果导入正确的话为什么未定义它。任何想法都将受到欢迎。 =(