Loading......
接上一篇文章,在创立完对应的模型后在数据初始化时需加载各模型的对应关系;
在 init 中的 initDB 中建立各模型之间的关系;
大概关系有如下几种(后续开发用到关系再添加):
官方文档:关联 | Sequelize 中文文档 | Sequelize 中文网
// A.hasOne(B); // A 有一个 B
// A.belongsTo(B); // A 属于 B
// A.hasMany(B); // A 有多个 B
// A.belongsToMany(B, { through: 'C' }); // A 属于多个 B , 通过联结表 C
首先将所需的模型对应的文件引入;
const User = require("../models/user");
const Article = require("../models/article");
const Comment = require("../models/comment");
const Tag = require("../models/tag");
const sequelize = require("../db/sequelize");
创建一个函数,在函数中书写模型的对应关系;
模型关系-用户-文章-评论-标签
// 用户与用户的关系
User.belongsToMany(User, {
through: "Followers",
as: "followers",
timestamps: false,
}); //用户拥有多个粉丝
//用户和文章的关系
User.hasMany(Article, {
onDelete: "CASCADE",
}); //一个用户有多个文章
Article.belongsTo(User); // 文章属于用户
User.belongsToMany(Article, {
// 用户可以喜欢多个文章
through: "Favorites",
timestamps: false,
});
Article.belongsToMany(User, {
// 文章可以被多个用户收藏
through: "Favorites",
timestamps: false,
});
//用户和评论的关系
User.hasMany(Comment, {
onDelete: "CASCADE",
}); // 一个用户可以有多个评论
Comment.belongsTo(User); // 评论属于用户
//文章和标签的关系
Article.belongsToMany(Tag, {
through: "TagList",
uniqueKey: false,
timestamps: false,
}); // 一个文章有多个标签
Tag.belongsToMany(Article, {
through: "TagList",
uniqueKey: false,
timestamps: false,
}); // 一个标签可以使用于多个文章
在创建完这些模型之间的关系后,将该函数放到初始化函数 initDB 中,让其在初始化的时候加载完毕,并且同步所有模型和关系。
//数据库建立连接
await dbConnection();
// 初始化 model 关系
initRelation();
// 同步所有模型和关系
await sequelize.sync({alter:true});
最后在终端中启动服务,测试结果;
详细代码:
initDB.js
const dbConnection = require("../db/connection.js");
const User = require("../models/user");
const Article = require("../models/article");
const Comment = require("../models/comment");
const Tag = require("../models/tag");
const sequelize = require("../db/sequelize");
//模型关系-用户-文章-评论-标签
// A.hasOne(B); // A 有一个 B
// A.belongsTo(B); // A 属于 B
// A.hasMany(B); // A 有多个 B
// A.belongsToMany(B, { through: 'C' }); // A 属于多个 B , 通过联结表 C
const initRelation = () => {
// 用户与用户的关系
User.belongsToMany(User, {
through: "Followers",
as: "followers",
timestamps: false,
}); //用户拥有多个粉丝
//用户和文章的关系
User.hasMany(Article, {
onDelete: "CASCADE",
}); //一个用户有多个文章
Article.belongsTo(User); // 文章属于用户
User.belongsToMany(Article, {
// 用户可以喜欢多个文章
through: "Favorites",
timestamps: false,
});
Article.belongsToMany(User, {
// 文章可以被多个用户收藏
through: "Favorites",
timestamps: false,
});
//用户和评论的关系
User.hasMany(Comment, {
onDelete: "CASCADE",
}); // 一个用户可以有多个评论
Comment.belongsTo(User); // 评论属于用户
//文章和标签的关系
Article.belongsToMany(Tag, {
through: "TagList",
uniqueKey: false,
timestamps: false,
}); // 一个文章有多个标签
Tag.belongsToMany(Article, {
through: "TagList",
uniqueKey: false,
timestamps: false,
}); // 一个标签可以使用于多个文章
};
const initDB = () => {
return new Promise(async (resolve, reject) => {
try {
//数据库建立连接
await dbConnection();
// 初始化 model 关系
initRelation();
// 同步所有模型和关系
await sequelize.sync({alter:true});
resolve();
} catch (error) {
console.log(error);
reject(error);
}
});
};
module.exports = initDB;
未完待续......