这篇文章主要介绍nodejs版orm库--sequelize是什么,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
sequelize
是nodejs版的orm库,用过laravelORM
的能很快能上手
const { Sequelize, DataTypes, Model, QueryTypes, Op } = require("sequelize");
const sequelize = new Sequelize("sqlite://sql.db", { logging: false });
class User extends Model {}
class Address extends Model {}
User.init(
{
// 在这里定义模型属性
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
unique: true,
// allowNull 默认为 true
validate: {
async isUnique(name) {
const res = await User.findOne({where: {name}})
if (res) throw new Error('用户名已存在')
},
// len: [1,2]
}
},
},
{
// 这是其他模型参数
sequelize, // 我们需要传递连接实例
// modelName: "User", // 我们需要选择模型名称
tableName:'users' // 表名,默认为模型名的复数单词
}
);
Address.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
unique: true,
// allowNull 默认为 true
},
},
{
sequelize,
modelName: "Address",
}
);
// 模型关系 多对多
User.belongsToMany(Address, { through: "userAddress", as:'addres' }); // through 代表中间表的名字,as是查询别名
Address.belongsToMany(User, { through: "userAddress" });
(async () => {
try {
// await sequelize.sync({ alter: true }); // 同步模型到数据库-创建表
// const user = await User.findOne({ where: { name: {[Op.like]:'%小%'} } }); // 基本查询
const [user] = await User.findOrCreate({where:{name:'小小'},include:'addres'}); // 顺带查询到关联模型的数据
const [address] = await Address.findOrCreate({where:{name:'小小de地址'}});
await user.addAddress(address); // 关联增加
console.log(user.toJSON());
} catch (e) {
console.log(e);
}
})();
以上是nodejs版orm库--sequelize是什么的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。