https://github.com/demopark/sequelize-docs-Zh-CN
安装
yarn add sequelize mysql mysql2 -s
连接
const sequelize = new Sequelize("test_orm", "root", "root", {
host: "localhost",
port: "3306",
dialect: "mysql"
});
定义模型
const Author = sequelize.define(
"author",
{
age: Sequelize.STRING(11),
name: Sequelize.STRING(20)
},
{
tableName: "author"
}
);
npm i -g sequelize-auto
sequelize-auto -d database -u user -x pwd -h host -p port
sequelize-auto -d test_orm -u root -x root -p 3306 -h localhost
MySQL
表关系定义
// 一对一
//每一篇 文章根据 author_id 对应一个作者
// 作者关联到文章 通过作者查文章
Author.hasOne(Article, { foreignKey: 'author_id' })
// 文章关联到文章 ,通过文章查作者
Article.belongsTo(Author, { foreignKey: 'author_id' })
// 一对多
// 每一个作者有多个文章
Author.hasMany(Article, { foreignKey: "author_id" });
// 多对多
查询
Project.findById(123).then(project => {
})
Project.findOne({ where: {title: 'aProject'} }).then(project => {
})
Project.findOne({
where: {title: 'aProject'},
attributes: ['id', ['name', 'title']]
}).then(project => {
})
Author.findAll()
.then(result => {
console.log(result);
res.type("json");
res.json(result);
})
.catch(err => {
res.status(500).end(`查询出错::${err.message}`);
});
Article.findAll({
include: [Author]
})
.then(result => {
res.type("json");
res.json({ status: "ok", result });
})
.catch(err => {
res.json({ message: err.message });
});
更新
Author.update(
{
name: "update_fdsafsdafdasfdsa"
},
{
where: { id }
}
)
.then(result => {
res.type("json");
res.json({ status: "ok" });
})
.catch(err => {
res.json({ message: "更新错误" });
});
插入
Author.create({ name: "name_add", age: 20 })
.then(result => {
console.log(result);
res.json({ status: "ok" });
})
.catch(e => {
res.json({ status: "error", message: e.message });
});
Article.bulkCreate(itemsList)
.then(result => {
res.json({ message: "插入成功",result:itemsList });
})
.catch(err => {
res.status(500).json({ message: "插入失败", errMsg: err.message });
});
删除
Author.destroy({
where: { id }
})
.then(result => {
res.type("json");
res.json({ status: "ok" });
})
.catch(err => {
res.json({ message: "删除错误" });
});