问题描述:

I have a few weeks working with Sequelize and I ran into this. I've already read other similar questions but nothing seems to help.

Let me show you my models:

Merchants.js

'use strict';

var Sequelize = require('sequelize');

var config = require(__base + '/server/config/config').provisioning;

var sequelize = new Sequelize(config.database, config.user, config.password, config);

var Merchants = sequelize.define('merchants', {

id: {

type: Sequelize.UUID,

primaryKey: true,

unique: true,

defaultValue: Sequelize.UUIDV4

},

name: {

type: Sequelize.STRING(255)

},

createdAt: {

type: Sequelize.DATE,

field: 'created_at'

},

//more attributes

}, {

classMethods: {

associate: function (models) {

Merchants.hasOne(models.Users, {foreignKey: 'merchantId'})

}

}

});

module.exports = Merchants;

Users.js

'use strict';

var Sequelize = require('sequelize');

var config = require(__base + '/server/config/config').provisioning;

var sequelize = new Sequelize(config.database, config.user, config.password, config);

var Users = sequelize.define('users', {

id: {

type: Sequelize.UUID,

primaryKey: true,

unique: true,

defaultValue: Sequelize.UUIDV4

},

merchantId: {

type: Sequelize.UUID,

field: 'merchant_id'

},

createdAt: {

type: Sequelize.DATE,

field: 'created_at'

},

// more attributes

}, {

classMethods: {

associate: function (models) {

Users.belongsTo(models.Merchants, { foreignKey: 'merchantId' });

}

}

});

module.exports = Users;

Then I'm trying to do this:

Users.findAll({

include: [{

model: Merchants,

where: { state: 'ACTIVATED' }

}]

}).then(function (users) {

console.log(users.length);

}).catch(function (err) {

console.log(err);

});

And I'm getting: [Error: merchants is not associated to users!]

I've done some of the stuff I've read in different questions but nothing seems to work. It might be a foolish thing, but as I said before, first time working with Sequelize.

网友答案:

Make sure that the associations are actually being set up - Do note that the associate method is not part of sequelize API, but is merely a common pattern - you have to make sure its actually called. For example with:

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

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

https://github.com/sequelize/express-example/blob/master/models/index.js

相关阅读:
Top