Home > Web Front-end > JS Tutorial > Nodejs version of orm library--sequelize

Nodejs version of orm library--sequelize

青灯夜游
Release: 2020-09-09 10:12:23
forward
2766 people have browsed it

This article will take you through the nodejs database orm extension-sequelize. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Nodejs version of orm library--sequelize

sequelize is the nodejs version of the ORM library. Those who have used laravelORM can get started quickly

[Video tutorial recommendation: node js tutorial]

Specific documentation

Simple code 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);
  }
})();
Copy after login

For more programming-related knowledge, please visit:

Programming Teaching! !

The above is the detailed content of Nodejs version of orm library--sequelize. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template