mysql - 序列化模型关系

标签 mysql node.js sequelize.js

我这里有 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;
};

有人可以举例说明如何设置从用户用户个人资料的1:N关系,即1个用户可以拥有N个用户配置文件,并且通过创建此关系,每当创建用户时,是否会在用户配置文件表下自动生成一条记录?

谢谢

最佳答案

做了一些研究 - 引用: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',
    });
  };

上面的代码在用户配置文件表中创建了一个外键,并且没有完成自动生成。

关于mysql - 序列化模型关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117509/

相关文章:

javascript - 将变量的值从测试传递到 Cypress 中的下一个

node.js - 如何在 Heroku 上的 Nodejs 应用程序中使用 "underscore"模块?

java - Node.js 和 Java

mysql - 使用环境变量进行本地 Sequelize 配置

mysql - 我怎样才能得到想要的结果?

php - WooCommerce 礼品卡插件实际上在哪里创建数据库记录?

mysql - 将时间戳转换为正确的格式

php - 修改分页排序方法以更改每页的行数

postgresql - Sequelize 不会创建外键作为约束

node.js - 使用 sequelize 在 postgres 中存储字符串数组?