sequelize-docs-Zh-CN icon indicating copy to clipboard operation
sequelize-docs-Zh-CN copied to clipboard

请问如何在创建了模型之后,如何通过 migrate 添加关联关系?

Open monkeym4ster opened this issue 7 years ago • 1 comments

目前状态

创建了 User 模型,以及 Profile 模型。

需求

给 user 模型和 profile 模型添加一对一关系。

已有模型 的情况之下,如何能通过 sequelize-cli 的 migrate 功能实现添加关联关系的操作呢?

我想我知道如何在 model 层面里进行关联关系的添加,但是目的是 「版本管理」 嘛。

// app/model/user.js
...
User.associate = () => User.hasOne(Profile);
...

// app/model/profile.js
...
Profile.associate = () => Profile.belongsTo(User);
...

Models

// app/model/user.js

module.exports = app => {
  const { STRING} = app.Sequelize;

  const User = app.model.define('User', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    username: STRING,
    password: STRING,
  });

  return User;
};
// app/model/profile.js

module.exports = app => {
  const { STRING, INTEGER } = app.Sequelize;

  const Profile = app.model.define('Profile', {
    description: STRING,
    user_id: INTEGER,
  });

  return Profile;
};

monkeym4ster avatar Sep 05 '18 09:09 monkeym4ster

a23f928ad797b9df09880ef06aa40e60 大佬可以告诉小弟,改了model的外键之后,生成的sql语句在哪里?怎么执行呢?怎么通过cli变更到数据库呢??? 看了无数文档,始终没有找到办法。

prettyboyweiwei avatar Nov 09 '18 09:11 prettyboyweiwei