Sequelize模型之间存在关联关系,这些关系代表了数据库中对应表之间的主/外键关系。基于模型关系可以实现关联表之间的连接查询、更新、删除等操作。本文将通过一个示例,介绍模型的定义,创建模型关联关系,模型与关联关系同步数据库,及关系模型的增、删、改、查操作。

数据库中的表之间存在一定的关联关系,表之间的关系基于主/外键进行关联、创建约束等。关系表中的数据分为1对1(1:1)、1对多(1:M)、多对多(N:M)三种关联关系。

Sequelize中建立关联关系,通过调用模型(源模型)的belongsTohasOnehasManybelongsToMany方法,再将要建立关系的模型(目标模型)做为参数传入即可。这些方法会按以下规则创建关联关系:

  • hasOne - 与目标模型建立1:1关联关系,关联关系(外键)存在于目标模型中。
  • belongsTo - 与目标模型建立1:1关联关系,关联关系(外键)存在于源模型中。
  • hasMany - 与目标模型建立1:N关联关系,关联关系(外键)存在于目标模型中。
  • belongsToMany - 与目标模型建立N:M关联关系,会通过sourceIdtargetId创建交叉表。

为了能够清楚说明模型关系的定义及关系模型的使用,我们定义如下4个模型对象:

  • 用户(User)-与其它模型存在1:11:NN:M
  • 用户登录信息(UserCheckin)-与User存在1:1关系
  • 用户地址(UserAddress)-与User存在N:1关系
  • 角色(Role)-与User存在N:M关系

这几个模型的E-R结构如下:

接下来上代码,代码和瓷土不符,请注意!


代码写的有点low,没办法,!

  1. /**
  2. * 大家就按照我的步骤来,一点一点,要有耐心哦
  3. * 我相信,最后肯定有你想要的!加油
  4. */
  5. //引入框架
  6. const Sequelize = require('sequelize');
  7. //创建ORM实例
  8. const sequelize = new Sequelize('sequlizedb', 'root', 'guoguo',
  9. {
  10. 'dialect': 'mysql', // 数据库使用mysql
  11. }
  12. );
  13. //验证连接
  14. sequelize
  15. .authenticate()
  16. .then(() => {
  17. console.log('链接成功');
  18. })
  19. .catch((error) => {
  20. console.log('链接失败' + error);
  21. })
  22. //模型的创建
  23.  
  24. const User = sequelize.define('user', {
  25. name: Sequelize.STRING,
  26. age: Sequelize.INTEGER,
  27. }, {
  28. freezeTableName: true,
  29. });
  30.  
  31. // User.create({
  32. // name: 'guo',
  33. // age: 25
  34. // })
  35. // .then((result) => {
  36. // console.log('=======添加成功===================');
  37. // console.log(result);
  38. // console.log('==========================');
  39.  
  40. // })
  41. // .catch((error) => {
  42. // console.log('==========================');
  43. // console.log('添加失败' + error);
  44. // console.log('==========================');
  45.  
  46. // });
  47.  
  48. // const Role=sequelize.define('role',{
  49. // name:{
  50. // type:sequelize.STRING,
  51. // }
  52. // },
  53. // {freezeTableName:true});
  54.  
  55. const Message = sequelize.define('message', {
  56. text: Sequelize.STRING,
  57. }, {
  58. freezeTableName: true,
  59. });
  60.  
  61. const Image = sequelize.define('image', {
  62. url: Sequelize.STRING,
  63. }, {
  64. freezeTableName: true,
  65. });
  66. //删除表
  67. // sequelize.drop()
  68. // .then((logging)=>{
  69. // console.log('==========================');
  70. // console.log('删除成功!'+logging);
  71. // console.log('==========================');
  72.  
  73. // })
  74. // .catch((error)=>{
  75. // console.log('==========================');
  76. // console.log('删除失败'+error);
  77. // console.log('==========================');
  78.  
  79. // });
  80.  
  81. //建立关系
  82. // Message.belongsTo(User);
  83. // Message.hasMany(Image);
  84. //同步到数据库
  85. // sequelize.sync({
  86. // force: true,
  87. // }).then(() => {
  88. // console.log('==========================');
  89. // console.log('同步成功');
  90. // console.log('==========================');
  91.  
  92. // }).catch(() => {
  93. // console.log('==========================');
  94. // console.log('同步失败');
  95. // console.log('==========================');
  96.  
  97. // });
  98.  
  99. //cudr
  100. function addUers(name, age) {
  101. User.create({
  102. name: name,
  103. age: age,
  104. }).then((log) => {
  105. log = JSON.stringify(log);
  106. console.log('==========================');
  107. console.log('增加用户成功' + log);
  108. console.log('==========================');
  109.  
  110. }).catch((error) => {
  111. console.log('==========================');
  112. console.log('增加用户失败' + error);
  113. console.log('==========================');
  114.  
  115. });
  116.  
  117. }
  118. function addMessage(userId, text) {
  119. Message.create({
  120. text: text,
  121. userId: userId,
  122. }).then((log) => {
  123. log = JSON.stringify(log);
  124. console.log('==========================');
  125. console.log('增加成功!' + log);
  126. console.log('==========================');
  127.  
  128. }).catch((error) => {
  129. console.log('==========================');
  130. console.log('增加失败!' + error);
  131. console.log('==========================');
  132.  
  133. });
  134. }
  135. function addImage(messageId, imageUrl) {
  136. Image.create({
  137. url: imageUrl,
  138. messageId: messageId,
  139. }).then((log) => {
  140. log = JSON.stringify(log);
  141. console.log('==========================');
  142. console.log('添加图片成功' + log);
  143. console.log('==========================');
  144.  
  145. }).catch((error) => {
  146. console.log('==========================');
  147. console.log('添加图片失败' + error);
  148. console.log('==========================');
  149.  
  150. });
  151. }
  152. //测试
  153. //addUers('杨雪娇',22);
  154. //addMessage(2, '杨雪娇发来的消息3');
  155.  
  156. // addImage(5,'http://3.png');
  157. // addImage(6,'http://4.png');
  158. // addImage(2,'http://2.png');
  159. // //
  160. function getAllMessage() {
  161. Message.findAll({
  162. where: {
  163. userId: 2
  164. },
  165. include: [
  166. {
  167. model: User,
  168. attributes: [
  169. 'id',
  170. 'name',
  171. ],
  172. },
  173. {
  174. model: Image,
  175. attributes: [
  176. 'id',
  177. 'url'
  178. ]
  179. }
  180. ],
  181. }).then((result) => {
  182. result = JSON.stringify(result);
  183. console.log('==========================');
  184. console.log(result);
  185. console.log('==========================');
  186.  
  187. }).catch((error) => {
  188. console.log('==========================');
  189. console.log('查询失败' + error);
  190. console.log('==========================');
  191.  
  192. });
  193. }
  194. //测试
  195. //getAllMessage();
  196. //删除消息
  197. function delMessage(userId, messageId) {
  198. Message.destroy({
  199. where: {
  200. userId: userId,
  201. id: messageId,
  202. },
  203.  
  204. }).then((log) => {
  205. log = JSON.stringify(log);
  206. console.log('==========================');
  207. console.log('删除消息成功!' + log);
  208. console.log('==========================');
  209.  
  210. }).catch((error) => {
  211. console.log('==========================');
  212. console.log('删除消息失败!' + error);
  213. console.log('==========================');
  214.  
  215. });
  216. }
  217. //测试
  218. //测试发现问题 如果不设置级联 则,从属message表的image表记录不会删除,而只是出现对应messageId 为NULL的现象
  219. //delMessage(2,4);
  220.  
  221. const Role = sequelize.define('role', {
  222. name: {
  223. type: Sequelize.STRING, allowNull: true,
  224. }
  225. }, {
  226. freezeTableName: true,
  227. });
  228.  
  229. //对于单个模型的同步
  230. // Role.sync().then((log) => {
  231. // log = JSON.stringify(log);
  232. // console.log('==========================');
  233. // console.log('Role表数据同步成功' + log);
  234. // console.log('==========================');
  235. // Role.create({
  236. // name: '管理员'
  237. // }).then((log) => {
  238. // log = JSON.stringify(log);
  239. // console.log('==========================');
  240. // console.log('添加的数据为' + log);
  241. // console.log('==========================');
  242.  
  243. // }).catch((error) => {
  244. // console.log('==========================');
  245. // console.log('添加数据失败' + error);
  246. // console.log('==========================');
  247.  
  248. // });
  249.  
  250. // }).catch((error) => {
  251. // console.log('==========================');
  252. // console.log('Role模型与表数据同步失败' + error);
  253. // console.log('==========================');
  254.  
  255. // });
  256.  
  257. //定义User1模型
  258. const User1 = sequelize.define('user1', {
  259. name: {
  260. type: Sequelize.STRING,
  261. validate: {
  262. notEmpty: true,
  263. len: [2, 30],
  264. }
  265. },
  266. age: {
  267. type: Sequelize.STRING,
  268. defaultValue: 21,
  269. validate: {
  270. isInt: {
  271. msg: '年龄必须是整数!',
  272. }
  273. }
  274.  
  275. },
  276. email: {
  277. type: Sequelize.STRING,
  278. validate: {
  279. isEmail: true,
  280. }
  281. },
  282. userpicture: Sequelize.STRING,
  283. }, {
  284. freezeTableName: true,
  285. });
  286. //
  287. //同步User1模型
  288. // User1.sync().then((log) => {
  289. // log = JSON.stringify(log);
  290. // console.log('==========================');
  291. // console.log('User1表数据同步成功' + log);
  292. // console.log('==========================');
  293. // }).catch((error) => {
  294. // console.log('==========================');
  295. // console.log('User1模型与表数据同步失败' + error);
  296. // console.log('==========================');
  297. // });
  298.  
  299. function addUser1(userInfo) {
  300. User1.create({
  301. name: userInfo.name,
  302. age:userInfo.age,
  303. email:userInfo.email,
  304. }).then((log) => {
  305. log = JSON.stringify(log);
  306. console.log('==========================');
  307. console.log('添加的数据为' + log);
  308. console.log('==========================');
  309.  
  310. }).catch((error) => {
  311. console.log('==========================');
  312. console.log('添加数据失败' + error);
  313. console.log('==========================');
  314.  
  315. });
  316. }
  317. const userInfo={
  318. name:'郭东生',
  319. //age:0.1,//Validation error: 年龄必须是整数!
  320. age:22,
  321. email:'7758@qq.com',
  322. //email:'7758',//Validation error: Validation isEmail on email failed
  323. }
  324. addUser1(userInfo);

Node.js ORM框架Sequlize之表间关系的更多相关文章

  1. Node.js ORM 框架 sequelize 实践

    最近在做团队的一个内部系统,这次使用的nodejs web框架是团队统一的hapi.js,而数据库依然是mysql,ORM 框架选用有着6000+ stars 的 sequelize.js,hapi- ...

  2. Node.js ORM框架Sequelize使用示例

    示例代码: const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'username' ...

  3. Node.js Express 框架

    Node.js Express 框架 Express 简介 Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP ...

  4. Node.js Express框架

    Express 介绍 Express是一个最小的,灵活的Node.js Web应用程序框架,它提供了一套强大的功能来开发Web和移动应用程序. 它有助于基于Node Web应用程序的快速开发.下面是一 ...

  5. 全端开发必备!10个最好的 Node.js MVC 框架

      Node.js 是最流行的 JavaScript 服务端平台,它允许建立可扩展的 Web 应用程序.Node.js 包含不同类型的框架,如 MVC 框架.全栈框架.REST API  以及大量的服 ...

  6. Koa – 更加强大的下一代 Node.js Web 框架

    Koa 是 Express 的开发团队设计的下一代 Web 框架,其目的是为 Web 应用程序提供更小,更具表现力,更坚实的基础.Koa 没有核捆绑任何中间件,并提供了一​​套优雅的方法,使服务器端开 ...

  7. 【360开源】thinkjs:基于Promise的Node.js MVC框架 (转)

    thinkjs是360奇舞团开源的一款Node.js MVC框架,该框架底层基于Promise来实现,很好的解决了Node.js里异步回调的问题.360奇舞团(奇虎75Team),是奇虎360公司We ...

  8. Node.js日志框架选型比較:Winston

    日志对于问题定位.调试,系统性能调优至关重要,尤其是系统复杂以及在线执行的情况下. 好的开发框架都会有一个可开启关闭/可配置记录级别的日志系统.我们从下面几个方面来做选型: 1. 每行日志都须要有准确 ...

  9. 十款最佳Node.js MVC框架

    十款最佳Node.js MVC框架摘要:Node.js是JavaScript中最为流行的框架之一,易于创建可扩展的Web应用.本文分享十款最佳的JavaScript框架. Node.js是JavaSc ...

随机推荐

  1. 在 ASP.NET MVC 中使用异步控制器

    线程池 一直想把项目改写成异步,但是ASP.NETMVC3下写的过于繁琐,.NET 4.5与ASP.NET MVC下代码写起来就比较简单了, MS好像也一直喜欢这样搞,每一个成熟的东西,都要演变好几个 ...

  2. JavaScript -- Window-Scroll

    -----037-Window-Scroll.html----- <!DOCTYPE html> <html> <head> <meta http-equiv ...

  3. mycat中间件--schema.xml配置文件详解

    schema.xml管理着MyCat的逻辑库.表.分片规则.DataNode以及DataSource.弄懂这些配置,是正确使用MyCat的前提. <?xml version="1.0& ...

  4. [Python学习笔记-006] 使用stomp.py校验JMS selector的正确性

    了解Jenkins的人都知道,JMS selector是基于SQL92语法实现的,本文将介绍使用stomp.py和ActiveMQ来校验JMS selector的正确性. Q: 什么是stomp.py ...

  5. 人人,金山西山居,腾讯互娱,微信,网易游戏offer及面经

    转自:http://www.itmian4.com/forum.php?mod=viewthread&tid=3985 首先感谢师兄在两年前发的贴([天道酬勤] 腾讯.百度.网易游戏.华为Of ...

  6. 【IT笔试面试题整理】丑数

    [试题描述]我们把只包含因子2.3和5的数称作丑数.求按从到大的顺序的第1500个丑数.例如6,8是丑数,而14不是,因为它包含因子7.习惯上把1当作第一个丑数. 根据丑数的定义,丑数应该是另一个丑数 ...

  7. 学了近一个月的java web 感想

    对于每天学习的新知识进行一定的总结,是有必要的. 之前我学的每一门知识,我都没有怎么总结自己的问题,也没有怎么去想想该怎样才能学的更好,把知识掌握的更牢固.从现在开始呢,我会每半个月,或每一个月总结总 ...

  8. CRM项目分析建表

    这个CRM项目是我们学习一年多以来,第一次团队合作完成的项目!之前的项目都是做半个月的,但是都是自己单独完成一套项目的!这次我们还是做半个月的!但是我们是分工合作的!自己所完成的内容都是不同的!我觉得 ...

  9. 线性回归浅谈(Linear Regression)

    在现实生活中普遍存在着变量之间的关系,有确定的和非确定的.确定关系指的是变量之间可以使用函数关系式表示,还有一种是属于非确定的(相关),比如人的身高和体重,一样的身高体重是不一样的.       线性 ...

  10. FFmpeg简易播放器的实现-最简版

    本文为作者原创:https://www.cnblogs.com/leisure_chn/p/10040202.html,转载请注明出处 基于FFmpeg和SDL实现的简易视频播放器,主要分为读取视频文 ...