3

我正在尝试了解 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.hasMany(Deadline) 时,用户原型应该自动获取 setDeadlines、getDeadlines、add/removeDeadline 方法。你可以帮帮我吗?

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

4

1 回答 1

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!')
                })
            })
        })
    })
})
于 2013-10-14T20:01:03.633 回答