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

标签 sequelize.js

我发现 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/

    相关文章:

    node.js - Sequelize 部署同步

    node.js - Sequelize 返回错误结果

    sql - 使用自定义连接表主键对 BelongsToMany 进行 Sequelize

    javascript - 如何在 Sequelize Model 中创建方法?

    node.js - Node/序列 : loading all models

    node.js - Sequelize,如何从连接表中检索特定字段

    sequelize.Model.Update 的 Typescript 接口(interface)不正确?

    node.js - 使用直通表更改 Sequelize 默认外键

    logging - sequelize 如何在记录时使用 bindparam 禁用输出 sql

    node.js - Sequelize 删除 JSON 中不存在的行