2016-07-07 40 views
0

我有幾周的時間和Sequelize一起工作,我遇到了這個問題。我已經閱讀過其他類似的問題,但似乎沒有任何幫助。錯誤:XModel未關聯到Sequelizejs上的Ymodel

讓我告訴你我的模型:

Merchants.js '使用嚴格的';

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; 

然後我試圖做到這一點:

Users.findAll({ 
    include: [{ 
     model: Merchants, 
     where: { state: 'ACTIVATED' } 
    }] 
    }).then(function (users) { 
    console.log(users.length); 
    }).catch(function (err) { 
    console.log(err); 
    }); 

而且我越來越:[Error: merchants is not associated to users!]

我已經做了一些的我在不同的問題閱讀的東西,但似乎沒有工作。這可能是一個愚蠢的事情,但正如我之前所說的,第一次與Sequelize合作。

回答

0

確保協會實際上是正在建立 - 請注意,associate方法不sequelize API的一部分,但僅僅是一個常見的模式 - 必須確保它的實際調用。例如有:

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

+0

這非常有意義。我多麼愚蠢。它的工作,謝謝! –