node.js - 将分离文件中的关联序列化

标签 node.js sequelize.js

我对 Sequelize 模型有问题。我无法在分离的文件中创建双向关联。所以我有这个简单的代码:

//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;
};

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

提前致谢...

最佳答案

关联可以这样写:

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

还可以运行以下命令来创建默认配置文件。
node_modules/.bin/sequelize init

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

关于node.js - 将分离文件中的关联序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58907052/

相关文章:

javascript - 在 apache 服务器上部署 React (3000) 和 Express (8000) 应用程序

iOS:如何在 Swift [NSString] 中显示特殊字符

node.js - express 虚拟主机 'argument handle is required'

javascript - 如何扩展 Sequelize 模型?

javascript - 使用 Javascript node.js 如何并行处理 For 循环?

javascript - AngularJS 将数据发布到 nodeJs/Sequelize

javascript - Sequelizejs promise 返回空对象

sequelize.js - 如何在 Sequelize 中从同一个表中加载多个外键行?

javascript - Sequelize classMethods 与 instanceMethods

javascript - 将 JavaScript 回调传递给在另一个线程中调用它的 FFI 函数是否安全?