我发现 Sequelize docs 很长而且很难理解,如果你使用的表不遵循他们的约定。
如果我有两个表:
people
(
people_id - uuid
name - text
)
parties
(
parties_id - uuid
people_id - uuid (foreign key)
)
我这样定义我的模型是否正确?
function getPeople()
{
let entity = {};
entity['people_id'] = {type: Sequelize.UUID, primaryKey: true, allowNull : false};
entity['name'] = Sequelize.TEXT;
return sequelize.define('dbo.people', entity, options);
}
function getParties()
{
let entity = {};
entity['parties_id'] = {type: Sequelize.UUID, primaryKey: true, allowNull : false};
entity['people_id'] =
{
type: Sequelize.UUID,
references: {model: getPeople(), key: 'people_id', deferrable: Sequelize.Deferrable.INITIALLY_DEFERRED}
};
const parties = sequelize.define('dbo.parties', entity, options);
parties.belongsTo(this.getPeople(), {foreignKey: 'people_id'});
return parties;
}
假设:
最佳答案
If I leave out the 'belongsTo' part then as I understand the docs it won't actually be an association, so I couldn't pull out related data in queries using include:[]
正确 - 并且只有belongsTo,您将只能执行
Parties.findAll(include People)
- 要以相反的方式执行此操作,您还需要设置反向关联。If I leave out the 'references' part then I have no way of specifying the local field name, 'people_id', to be different from the convention 'peopleId' nor a way of setting 'deferrable'
是的
I assume I can use getPeople() to return a class for use in foreign keys and it doesn't have to be a singleton
如果您有同一个模型的多个实例,您可能会遇到微妙的问题 - 一般模式是在单独的文件中定义每个模型并要求它一次。在需要访问模型的任何地方,您都可以从 sequelize 实例访问它 - 请参阅 https://github.com/sequelize/express-example
关于sequelize.js - 这是在 Sequelize 中定义表关系的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37297797/