Sequelize关联会出错

时间:2013-02-24 04:28:00

标签: mysql node.js sequelize.js

我想通过“Sequelize”生成表格的“代码优先”,这里我的代码是

var  Sequelize = require('sequelize');

exports.createTable = function(req,res){     var sequelize = new Sequelize('myblog','root','');

var Blog = sequelize.define('Blog',{
    // the blog id
    bid: { type: Sequelize.INTEGER, allowNull: false, autoIncrement: true ,primaryKey: true },
    // bname
    btitle: { type: Sequelize.STRING, allowNull: false },
    // blog Content
    bcontent: { type: Sequelize.TEXT, allowNull: false },
    // blog date
    bdate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }
});

var User = sequelize.define('User',{
    // uid
    uid: { type: Sequelize.INTEGER, allowNull: false ,autoIncrement: true, primaryKey: true },
    // uname
    uname: { type: Sequelize.TEXT, allowNull: false, },
    // register date
    regDate: { type: Sequelize.DATE, allowNull: false, defaultValue: Sequelize.NOW },

});

Blog.hasMany(User);
User.hasMany(Blog);

Blog.sync();
User.sync();

var blog = Blog.build({
    btitle: 'this is a title',
    bcontent: 'this is a Content!',
    bdate: new Date()
});

var user1 = User.build({
    uname: 'www',
    uregDate: new Date()
});

var user2 = User.build({
    uname: 'www2',
    uregDate: new Date()
});

blog
    .save()
    .success(function () {
        console.log('blog save suc');
    });

user1
    .save()
    .success(function () {
        console.log('user save suc')
    }); 
user2
    .save()
    .success(function () {
        console.log('user save suc')
    }); 

blog
    .setUsers([user1,user2])    
    .success(function () {
        console.log('saved')
    })
    .error(function (err) {
        console.log(err);
    });
// blog.getUsers()
//  .success(function (ascUser) {
//      console.log(ascUser);
//  }); 


sequelize
    .sync()
    .success(function () {
        res.send('createTable ok!');
    })
    .error(function () {
        res.send('createTable falied!');    
    });

}

我收到错误:错误:ER_BAD_FIELD_ERROR:'where子句中的未知列'User.id'....谁可以帮助我?很多

1 个答案:

答案 0 :(得分:1)

bid和uid有哪些字段? Sequelize会自动为你制作一个id,所以如果这些都被用来,你应该删除它们,除非它们是必需的。我不是肯定的,但我猜测如果你创建一个自动递增的主键,Sequelize可能不会自动创建一个id字段,认为你想要使用它。但是协会希望该列是id。再次,不确定为什么,但我敢打赌,如果你删除那些出价和uid字段,它将按预期工作。