I want to "code-first" which generate table by the "Sequelize",here my code is
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!');
});
}
And I got the error: Error:ER_BAD_FIELD_ERROR:Unknown column 'User.id' in 'where clause。。。。who can help me? thx a lot
What are the fields bid and uid for? Sequelize will automatically make an id for you, so if that's all those are being used for, you should delete them unless they are required. I'm not positive, but I'm guessing that if you create an auto-incrementing primary key that Sequelize may not automatically create an id field, thinking that you want to use that instead. But associations expect the column to be id. Again, not sure on why, but I bet if you remove those bid and uid fields, it'll work as you expect.