Skip to content

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

@monkeym4ster

Description

@monkeym4ster

目前状态

创建了 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;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions