ORM技术:Object-Relational Mapping,把关系数据库的表结构映射到对象上
在最近的一个项目中,选择 Node 的 ORM 框架来操作数据库,这样,我们写的都是 JavaScript 对象,Sequelize 帮我们把对象变成数据库中的行。
错误信息
在使用 sequelize 链接 mysql8 时,出现了如下的错误:
主要的报错信息是这段代码:
Unhandled rejection SequelizeConnectionError: Client does not support authentication protocol requested by server; consider upgrading MySQL client
出错原因
导致出错的原因是 最新的 mysql 模块并未完全支持 MySQL8 的 “caching_sha2_password” 加密方式,而 “caching_sha2_password” 是 MySQL8 中的默认加密方式。
解决方法
重新修改用户 root 的密码,并指定 mysql 模块能够支持的加密方式
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';
Query OK, 0 rows affected (0.03 sec)
上述语句,显式指定了 mysql_native_password 的加密方式,这种加密方式在 mysql 模块中是支持的
然后我们重新运行应用,运行成功:
程序代码
(async () => {
// 1:N关系
const Sequelize = require("sequelize");
// 建立连接
const sequelize = new Sequelize("kaikeba", "root", "sheng14@xin1066", {
host: "localhost",
dialect: "mysql",
});
const Fruit = sequelize.define("fruit", { name: Sequelize.STRING });
const Category = sequelize.define("category", { name: Sequelize.STRING });
// 定义一对多关系,Fruit 与 Category 是一对多的关系,Fruit 是一对多中的 一,Category 是一对多中的 多
Fruit.FruitCategory = Fruit.belongsToMany(Category, {
through: "FruitCategory"
});
// 插入测试数据
sequelize.sync({ force: true }).then(async () => {
await Fruit.create(
{
name: "香蕉",
categories: [{ id: 1, name: "热带" }, { id: 2, name: "温带" }]
},
{
include: [Fruit.FruitCategory]
}
);
// 多对多联合查询
const fruit = await Fruit.findOne({
where: { name: "香蕉" }, // 通过through指定条件、字段等
include: [{ model: Category, through: { attributes: ['fruitId', 'categoryId'] } }]
});
console.log('--fruit---', fruit)
})
})()
seuqelize 中文文档:demopark.github.io/sequelize-d…