gpt4 book ai didi

sequelize.js - 这是在 Sequelize 中定义表关系的正确方法吗?

转载 作者:行者123 更新时间:2023-12-03 22:23:55 24 4
gpt4 key购买 nike

我发现 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;
}

假设:
  • 如果我省略了“belongsTo”部分,那么据我所知,它实际上并不是一个关联,因此我无法使用 include:[]
  • 在查询中提取相关数据
  • 如果我省略了“references”部分,那么我就无法指定本地字段名称“people_id”与约定“peopleId”不同,也无法设置“deferrable”
  • 我假设我可以使用 getPeople() 返回一个用于外键的类,并且它不必是单例
  • 最佳答案

    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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com