Sequalize关联看不到模型

时间:2018-01-31 22:14:27

标签: javascript node.js sequelize.js

您好我在关联"字段"中的模型可见性方面存在问题。有代码可以显示问题: 当我做这样的事情时:

Applications.js

'use strict';    
module.exports = (sequelize, DataTypes) => {
  var Applications = sequelize.define('Applications', {
    id: { type:DataTypes.INTEGER, primaryKey: true},
    team_id:DataTypes.INTEGER,
    paid:DataTypes.INTEGER
  }, {
      freezeTableName: true,
      tableName: 'applications',
      timestamps:false,
      classMethods: {
      associate: function(models) {
          Applications.belongsTo(models.Teams, {foreignKey:'team_id', as: 'team'});
      }
    }
  });

  Applications.sync({force: false});
  return Applications;
};

Teams.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  var Teams = sequelize.define('Teams', {
    id: { type:DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
    name: DataTypes.STRING,
    phone: DataTypes.STRING
  }, {
    freezeTableName: true,
    tableName:'teams',
    timestamps:false,
    classMethods: {
      associate: function(models) {
          Teams.hasOne(models.Applications, {foreignKey:'team_id', as: 'team'});
      }
    }
  });

  Teams.sync({force: false});
  return Teams;
};

Router.js

router.get('/applications', function(req, res, next) {
    models.Applications.findAll({where:{id: 7},include:['team']}).then(function (value) { res.send(value) });   
});

然后我得到错误,说这两个模型之间没有关联。但是当我向路由器添加关联时,一切都开始工作。 正在运作的代码:

models.Teams.hasOne(models.Applications, {foreignKey:'team_id', as: 'team'});
models.Applications.belongsTo(models.Teams, {foreignKey:'team_id', as: 'team'});

router.get('/applications', function(req, res, next) {
    models.Applications.findAll({where:{id: 7},include:['team']}).then(function (value) { res.send(value); });
});

1 个答案:

答案 0 :(得分:0)

应该调用classMethods的关联函数来创建关联。

见以下代码供参考 -

Object.keys(db).forEach(function(modelName) {
   if ("associate" in db[modelName]) {
       db[modelName].associate(db);
   }
});
// Here all associate function are called one by one.

您已定义了关联功能,但在同步之前未执行。

通常,我们创建一个index.js文件来关联所有关联,并在该文件中调用每个模型的关联函数。