模型关系概要

A.hasOne(B); // A 有一个 B A.belongsTo(B); // A 属于 B A.hasMany(B); // A 有多个 B A.belongsToMany(B, { through: ‘C’ }); // A 属于多个 B , 通过联结表 C


同步模型关系

  1. const dbConnection = require('../db/connection');
  2. const sequelize = require('../db/sequelize')
  3. const User = require('../models/User')
  4. const Article = require('../models/Article')
  5. const Tag = require('../models/Tag')
  6. const Comment = require('../models/Comments')
  7. const initRelition = () => {
  8. //用户-文章:一对多
  9. User.hasMany(Article, {
  10. onDelete: "CASCADE", // CASCADE 小瀑布 ,当删除用户时候 关联的文章 也会删除
  11. });
  12. Article.belongsTo(User);
  13. //文章-标签:多对多
  14. Article.belongsToMany(Tag, {
  15. through: "TagList",
  16. uniqueKey: false,
  17. timestamps: false,
  18. });
  19. Tag.belongsToMany(Article, {
  20. through: "TagList",
  21. uniqueKey: false,
  22. timestamps: false,
  23. });
  24. //文章-评论:一对多
  25. Article.hasMany(Comment, { onDelete: "CASCADE" });
  26. Comment.belongsTo(Article);
  27. //用户-评论:一对多
  28. //一个用户可以有多个评论
  29. //一个评论属于某个用户
  30. User.hasMany(Comment, { onDelete: "CASCADE" });
  31. Comment.belongsTo(User);
  32. //用户-用户 关注:多对多
  33. //一个用户可以关注多个用户
  34. //一个用户可以被多个用户关注
  35. User.belongsToMany(User, {
  36. through: "Followers",
  37. as: "followers",
  38. timestamps: false,
  39. });
  40. //用户 - 文章 (喜欢):多对多
  41. User.belongsToMany(Article, { through: "Favourites", timestamps: false });
  42. Article.belongsToMany(User, { through: "Favourites", timestamps: false });
  43. };
  44. const initDB = () => {
  45. return new Promise(async (resolve,reject)=>{
  46. try {
  47. //连接数据库
  48. await dbConnection();
  49. // 初始化model关系
  50. initRelition()
  51. //自动同步所有模型
  52. await sequelize.sync({ alter: true });
  53. resolve()
  54. } catch (error) {
  55. console.log(error);
  56. reject(error)
  57. }
  58. })
  59. };
  60. module.exports = initDB;
  • User.sync() - 如果表不存在,则创建该表(如果已经存在,则不执行任何操作)
  • User.sync({ force: true }) - 将创建表,如果表已经存在,则将其首先删除
  • User.sync({ alter: true }) - 这将检查数据库中表的当前状态(它具有哪些列,它们的数据类型等),然后在表中进行必要的更改以使其与模型匹配.