nodejs版的orm库--sequelize


本文摘自PHP中文网,作者青灯夜游,侵删。

本篇文章带大家了解一下nodejs数据库orm扩展-sequelize。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

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

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

具体文档

  • 官网
  • github

简单代码demo

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

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的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

浅谈nodejs中的模块规范

深入了解调试nodejs程序的方法

详解nodejs+nest实现的短链接服务

如何使用nodejs实现路由功能

vue nodejs 什么区别

23个需要了解的十分有用的nodejs库(推荐)

nodejs学习之了解域名解析模块dns

详解检测和升级项目中node依赖的方法

初步了解nodejs中的异步i/o

浅谈nodejs连接mysql数据库的方法

更多相关阅读请进入《nodejs》频道 >>




打赏

取消

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

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

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

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...