【问题标题】:Sequelize Model Relationship续集模型关系
【发布时间】:2018-12-09 13:55:04
【问题描述】:

我这里有 2 个模型 -

user.js

module.exports = (sequelize, DataType) => {

  const User = sequelize.define('user', {
    id: {
      autoIncrement: true,
      primaryKey: true,
      type: DataType.INTEGER
    },
    username: {
      type: DataType.STRING,
      unique: true,
      validate: {
        len:
          { args: [4, 20], msg: "Username should be contain 4-20 characters." },
        isAlphanumeric:
          { msg: "Only letters and numbers are allowed" }
      }
    },
    email: {
      type: DataType.STRING,
      unique: true,
      validate: {
        isEmail:
          { msg: "Provide proper email" }
      }
    },
    password: DataType.STRING,
    emailverified: DataType.BOOLEAN
  });

  User.associate = function (models) {
    // associations can be defined here
  };

userprofile.js

module.exports = (sequelize, DataTypes) => {
  var userprofile = sequelize.define('userprofile', {
    nickName: DataTypes.STRING,
    firstName: DataTypes.STRING,
    middleName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    gender: DataTypes.INTEGER,
    age: DataTypes.INTEGER,
    country: DataTypes.INTEGER,
    steamUrl: DataTypes.STRING,
    city: DataTypes.INTEGER,
    status: DataTypes.STRING
  }, {});
  userprofile.associate = function (models) {
    // associations can be defined here
  };
  return userprofile;
};

有人可以举例说明如何设置从 useruserprofile 的 1:N 关系,即 1 个 user 可以有 N 个userprofiles 并且通过创建这种关系,每当创建 user 时,是否会在 userprofiles 表下自动生成一条记录?

谢谢

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    做了一些研究 - 参考:https://github.com/sequelize/express-example/blob/master/models/user.js

    module.exports = (sequelize, DataType) => {
    
      const User = sequelize.define('user', {
        id: {
          autoIncrement: true,
          primaryKey: true,
          type: DataType.INTEGER
        },
        username: {
          type: DataType.STRING,
          unique: true,
          validate: {
            len:
              { args: [4, 20], msg: "Username should be contain 4-20 characters." },
            isAlphanumeric:
              { msg: "Only letters and numbers are allowed" }
          }
        },
        email: {
          type: DataType.STRING,
          unique: true,
          validate: {
            isEmail:
              { msg: "Provide proper email" }
          }
        },
        password: DataType.STRING,
        emailverified: DataType.BOOLEAN
      });
    
      User.associate = (models) => {
        User.hasMany(models.userprofile, {
          foreignKey: 'userid',
        });
      };
    

    上面的代码在userprofile表中创建了一个外键,并没有自动生成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-16
      • 2018-02-28
      • 2020-05-30
      • 2017-09-06
      • 2015-12-25
      • 2018-10-27
      • 1970-01-01
      • 2018-08-04
      相关资源
      最近更新 更多