辅助方法和协会包括不工作sequelize

时间:2017-07-25 20:32:10

标签: mysql node.js sequelize.js

使用belongsTo / hasMany时,我无法调用sequelize应该生成的辅助方法。我不能急于加载一张桌子。 在尝试运行帮助器方法时,我收到一条消息,说没有这样的方法,并且当尝试使用findAll with include传递另一个表时它表示表没有关联,请参阅下面的详细信息:

模型目录:

targetSdkVersion

ticket.js

./models
--ticket.js
--category.js
--index.js

category.js

'use strict';

module.exports = function(sequelize, DataTypes) {
  var Ticket = sequelize.define('Ticket', {
    // category_id: DataTypes.INTEGER,
    subject: DataTypes.STRING,
    description: DataTypes.TEXT,
    requester_name: DataTypes.STRING,
    requester_email: DataTypes.STRING,
    owner_email: DataTypes.STRING,
    status: {
      type: DataTypes.ENUM,
      values: ['opened', 'in progress', 'closed']
    }
  }, {
    underscored: true,
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        Ticket.belongsTo(models['Category']);
        Ticket.hasMany(models['Interaction']);
      }
    }
  });

  return Ticket;
};

index.js

'use strict';

module.exports = function(sequelize, DataTypes) {
  var Category = sequelize.define('Category', {
    name: DataTypes.STRING
  }, {
    underscored: true,
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        Category.hasMany(models['Ticket']);
      }
    }
  });
  return Category;
};

然后我为模型创建常量:

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.json')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

尝试调用Ticket.getCategory()时,如下所示:

const models = require('../models'),
    Ticket = models['Ticket'],
    Category = models['Category'];

我明白了:

Ticket.findById(req.params.ticket_id).then((ticket) => {
        ticket.getCategory().then((category)=>{
            ticket['category'] = category;
            res.json(ticket);
        });
    });

如果我尝试使用预先加载,如下所示:

Executing (default): SELECT `id`, `subject`, `description`, `requester_name`, `requester_email`, `owner_email`, `status`, `created_at`, `updated_at` FROM `Tickets` AS `Ticket` WHERE `Ticket`.`id` = '1';
Unhandled rejection TypeError: ticket.getCategory is not a function

我明白了:

Ticket.findAll({where:{id:req.params.ticket_id},include:[Category]}).then((ticket) => {
    res.json(ticket);
});

我做错了什么?

提前致谢!

2 个答案:

答案 0 :(得分:1)

问题是您的关联没有完全完成。您需要指定外键。例如:

module.exports = function(sequelize, DataTypes) {
  var Ticket = sequelize.define('Ticket', {
    //blablabla
  }, {
    underscored: true,
    classMethods: {
      associate: function(models) {
        // here specify which are your foreign keys
        // category_id is just to illustrate
        Ticket.belongsTo(models['Category'], {foreignKey: category_id});
        Ticket.hasMany(models['Interaction'], {foreignKey: something_id});
      }
    }
  });

  return Ticket;
};

在这种情况下,还需要在对应物,类别和交互中完成。然后你就可以使用续集魔法

答案 1 :(得分:1)

如你所说,你正在使用seqielize ^ 4.2.0,这是主要的更新API几乎没有变化。'

在版本4中,您不应该通过classMethods对象添加类方法,而应该这样做。

var Ticket = sequelize.define('Ticket', {
    // category_id: DataTypes.INTEGER,
    subject: DataTypes.STRING,
    description: DataTypes.TEXT,
    requester_name: DataTypes.STRING,
    requester_email: DataTypes.STRING,
    owner_email: DataTypes.STRING,
    status: {
      type: DataTypes.ENUM,
      values: ['opened', 'in progress', 'closed']
    }
  }, {
    underscored: true,
});

Ticket.associate = function(models) {
    // associations can be defined here
    Ticket.belongsTo(models['Category']);
    Ticket.hasMany(models['Interaction']);
};

您可以阅读如何从续集3升级到4 here