【问题标题】:sequelize associations in separated files在单独的文件中续集关联
【发布时间】:2019-11-19 06:50:39
【问题描述】:

我对续集模型有疑问。我无法在单独的文件中创建双向关联。所以我有这个简单的代码:

//file one..
module.exports = function (sequelize, DataTypes) {
  //models
  const Author = sequelize.import(__dirname + '/Author');

  const Image = sequelize.define('Image', {
    id: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false,
    },
    author_id: {
      type: DataTypes.INTEGER,
      required:true,
      references:{
        model:Author,
        key:'id'
      },
    },
}, {
    tableName: 'image',
});

  //associations
  Image.belongsTo(Author);


  return Image;
};



//file two...
module.exports = function init(sequelize, DataTypes) {
  //models
  const Image = sequelize.import(__dirname + '/Image');

  // fields
  const Author = sequelize.define('Author', {
        id: {
          type: DataTypes.INTEGER,
          primaryKey: true,
          autoIncrement: true,
          allowNull: false,
        },
        username: {
          type: DataTypes.STRING(30),
          allowNull: false,
          unique: true,
        }
   },
      {
        tableName: 'author',
      });

  Author.hasMany(Image);

  return Author;
};

这不起作用。我得到了最大的堆栈调用。我什至不能导入这两个模型中的任何一个。如果我从两个文件之一中删除关联,它就像一个魅力。但我真的需要这种双向关联。

提前谢谢...

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    关联可以这样写:

    Aurthor.associate=(models)=>
    {
     Author.hasMany(Image);
    }
    

    同时运行以下命令来创建默认配置文件。

    node_modules/.bin/sequelize init
    

    这将生成一些文件夹 config/config.js、seeders、models/index.js、迁移。

    【讨论】:

      【解决方案2】:

      阿里加图。问题是关于 sequelize.import(),当我把它放在两个模型中时,它会创建一个无限循环。但是您的想法有助于知道我在该函数中导入了我需要的模型,并在需要时调用它。这真的很有帮助。谢谢

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-09
        • 1970-01-01
        • 1970-01-01
        • 2017-05-30
        • 1970-01-01
        • 2019-02-12
        • 1970-01-01
        相关资源
        最近更新 更多