【问题标题】:do sequelize associations do anything on the DB sidedo sequelize associations 在数据库端做任何事情
【发布时间】:2019-09-18 00:22:16
【问题描述】:

我在最近的项目中经常使用 sequelize,我很好奇关联与迁移的幕后情况。例如,当我生成 2 个模型时:

user = {
  id,
  name,
}

post = {
  id,
  name,
}

然后我生成一个迁移以添加关联的列:

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.addColumn(
      'posts',
      'userId', // name of the key we're adding
      {
        type: Sequelize.UUID,
        references: {
          model: 'users', // name of Target model
          key: 'id', // key in Target model that we're referencing
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
      }
    );
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.removeColumn(
      'posts', // name of Source model
      'userId' // key we want to remove
    );
  }
};

如果上面的迁移将实际的userId 列添加到posts 表中,模型中的associate 方法会做什么?

模型中associate 方法的示例:

module.exports = (sequelize, DataTypes) => {
  const post = sequelize.define('post', {
    name: DataTypes.TEXT
  }, {});
  post.associate = function(models) {
    post.belongsTo(models.user);
  };
  return post;
};

这提出了一个更大的问题,如果 associate 方法最终在 db 中创建实际的外键列,那么是创建外键列所必需的中间迁移(如上所示,它创建外键列) ?

【问题讨论】:

    标签: javascript orm sequelize.js


    【解决方案1】:

    TL;DR: Sequelize Associations 在数据库端不做任何事情,这意味着它们不能(创建表、添加列、添加约束等)

    免责声明:我可能没有涵盖 在这个答案中,这只是一个摘要。

    1) 这是我如何区分 ModelMigration基于功能):

    • Migration(在 DB 上创建表、添加约束等)
    • Model 使您作为开发人员可以更轻松地与 DB 上与 Model(这是为其定义的模型)对应的表进行交互,例如:User 模型可以帮助您无需编写 SQL 查询即可与 Users 表进行交互。

    2) Associate 方法为您提供了两种特殊功能,即 lazyLoadingeagerLoading,它们都可以让您免去通过原始 SQL 查询手动执行 Joins 的麻烦。
    又是这样:“模型让您不必自己编写原始 SQL 查询。”

    【讨论】:

      【解决方案2】:

      虽然这里没有详细回答问题,there's a decent description关于associations文件夹下sequelize github repo中的关联

      评论说:

      创建关联会为属性添加外键约束

      此外,以下提示实际上是从关联中生成列:

       * To get full control over the foreign key column added by sequelize,
       * you can use the `foreignKey` option. It can either be a string, 
       * that specifies the name, or and object type definition,
       * equivalent to those passed to `sequelize.define`.
       *
       * ```js
       * User.hasMany(Picture, { foreignKey: 'uid' })
       * ```
       *
       * The foreign key column in Picture will now be called `uid` 
       * instead of the default `userId`.
       *
       * ```js
       * User.hasMany(Picture, {
       *   foreignKey: {
       *     name: 'uid',
       *     allowNull: false
       *   }
       * })
       * ```
      

      【讨论】:

        猜你喜欢
        • 2015-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多