• 技术文章 >web前端 >js教程

    nodejs版的orm库--sequelize

    青灯夜游青灯夜游2020-09-09 10:12:23转载620
    本篇文章带大家了解一下nodejs数据库orm扩展-sequelize。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

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

    【视频教程推荐:node js教程

    具体文档

    简单代码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);
      }
    })();

    更多编程相关知识,可访问:编程教学!!

    以上就是nodejs版的orm库--sequelize的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:segmentfault,如有侵犯,请联系admin@php.cn删除
    专题推荐:nodejs orm sequelize
    上一篇:20个常见jQuery面试题和答案(分享) 下一篇:Mac和Windows下如何使用nvm安装和管理多个版本的node.js?
    大前端线上培训班

    相关文章推荐

    • 深入解析 Node.js 的回调队列• Deno中如何使用 Node 模块?• Controller层中Node怎么进行数据校验?• nodejs适合做些什么?• Linux环境下如何更新node版本(升级)

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网