百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> nodejs版的orm库--sequelize
分享文章到:

nodejs版的orm库--sequelize

发布时间:09/01 来源:未知 浏览: 关键词:
本篇文章带大家理解一下nodejs数据库orm扩展-sequelize。有必然的参照 价值,有需要的伴侣可以参照 一下,但愿对大家有所帮忙。

sequelize是nodejs版的orm库,用过laravelORM的能很快能上手

【视频教程引荐:node js教程 】

详细文档

  • 官网
  • github

简便代码demo

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);
  }
})();
打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有151人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板