sequelize模型关系

8e2ybdfx  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(312)

我这里有两个模型-
用户.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
  };

用户配置文件.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;
};

有人能举一个例子说明如何从用户到用户配置文件设置1:n的关系吗?即,一个用户可以有n个用户配置文件,并且通过创建这个关系,每当创建一个用户时,在userprofiles表下会自动生成一个记录吗?
谢谢您

thtygnil

thtygnil1#

做了一些研究-参考: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表中创建了一个外键,并且没有自动生成。

相关问题