gpt4 book ai didi

mysql - Sequelize 关联出现错误

转载 作者:行者123 更新时间:2023-11-29 14:01:03 25 4
gpt4 key购买 nike

我想“代码优先”,通过“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!');
});

}

我得到了错误:Error:ER_BAD_FIELD_ERROR:Unknown columns 'User.id' in 'where Clause。。。。谁能帮助我?非常感谢

最佳答案

bid 和 uid 字段的作用是什么? Sequelize 会自动为你创建一个 id,所以如果这就是所有这些的用途,你应该删除它们,除非它们是必需的。我并不肯定,但我猜测如果您创建一个自动递增主键,Sequelize 可能不会自动创建 id 字段,认为您想使用它。但协会希望该列是 id。同样,不确定为什么,但我敢打赌,如果您删除这些 bid 和 uid 字段,它会按您的预期工作。

关于mysql - Sequelize 关联出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15048668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com