如何在Sequelize中与协会合作

时间:2013-10-14 19:44:45

标签: javascript node.js sequelize.js

我想了解Sequelize,我对关联有一点小问题。请看下面的代码:

用户模型:

var Sequelize = require("sequelize");

module.exports = function (sequelize) {
    var User = sequelize.define('user', {
        id:{ type:Sequelize.INTEGER.UNSIGNED, autoIncrement:true, allowNull:false, primaryKey:true},
        name:{ type:Sequelize.STRING(50), defaultValue:''},
        email:Sequelize.STRING(50),
        password:Sequelize.STRING(256)
    });

    return User;
};

截止日期模型:

var Sequelize = require("sequelize");

module.exports = function (sequelize) {
    var User = require("./user")(sequelize),
        Deadline = sequelize.define('deadline', {
            id:{ type:Sequelize.INTEGER.UNSIGNED, autoIncrement:true, allowNull:false, primaryKey:true},
            name:{ type:Sequelize.STRING(255)}
        });

    User.hasMany(Deadline);

    return Deadline;
};

和不让我睡不好的代码:

var sequelize = require('./app/mysqlConnection'),
    User = require("./app/models/user")(sequelize),
    Deadline = require("./app/models/deadline")(sequelize);

sequelize.drop().success(function () {
    sequelize.sync().success(function () {

        var user = User.build({password:'bar', email:'ser'}),
            dead = Deadline.build({name:'learn js'});

        user.addDeadline(dead);

在最后一行我得到了

TypeError: Object [object Object] has no method 'addDeadline'
    at null.<anonymous> (C:\projects\deadline\dbsynch.js:11:14)
    at EventEmitter.emit (events.js:106:17)
    at module.exports.finish (C:\projects\deadline\node_modules\sequelize\lib\query-chainer.js:138:30)
    at exec (C:\projects\deadline\node_modules\sequelize\lib\query-chainer.js:92:16)
    at onSuccess (C:\projects\deadline\node_modules\sequelize\lib\query-chainer.js:65:11)
    at null.<anonymous> (C:\projects\deadline\node_modules\sequelize\lib\query-chainer.js:86:15)
    at EventEmitter.emit (events.js:95:17)
    at null.<anonymous> (C:\projects\deadline\node_modules\sequelize\lib\dao-factory.js:195:41)
    at EventEmitter.emit (events.js:95:17)
    at null.<anonymous> (C:\projects\deadline\node_modules\sequelize\lib\query-interface.js:162:19)

根据文档,当我通知User有关User.hasMany(截止日期)时,User原型应自动获取setDeadlines,getDeadlines,add / removeDeadline方法。你可以帮帮我吗?

顺便说一句 “sequelize”:“~2.0.0-beta.0”,

1 个答案:

答案 0 :(得分:3)

试试这个:

sequelize.drop().success(function () {
    sequelize.sync().success(function () {

        User.create({password:'bar', email:'ser'}).success(function(user) {
            Deadline.create({name:'learn js'}).success(function(deadline) {
                user.addDeadline(deadline).success(function() {
                    console.log('coolio!')
                })
            })
        })
    })
})