资讯专栏INFORMATION COLUMN

4.2 数据库表/Sequelize Mysql-博客后端Api-NodeJs+Express+My

nicercode / 1035人阅读

</>复制代码

  1. 功能梳理完了以后,咱们就可以开始数据库表设计了:

数据库表图:

首先打开Navicat Premium 创建数据库 blog

配置如下:

</>复制代码

  1. 课前学习:
    1、Sequelize 中文API文档【强烈推荐】https://itbilu.com/nodejs/npm...
    2、Sequelize 和 MySQL 对照
    https://segmentfault.com/a/11...
    3、使用Sequelize
    http://www.liaoxuefeng.com/wi...
    4、Sequelize API
    https://sequelize.readthedocs...
    5、关于“时间”的一次探索
    https://segmentfault.com/a/11...

在blogNodejs/models 下

首先新建 mysql.js 进行mysql连接配置(基于Sequelize)

</>复制代码

  1. var config = require("config-lite");//引入灵活配置文件
  2. var Sequelize = require("sequelize");.//引入Sequelize
  3. var Mysql = new Sequelize(config.mysql.database, config.mysql.user, config.mysql.password, {
  4. host: config.mysql.host, //数据库服务器ip
  5. dialect: "mysql", //数据库使用mysql
  6. port: 3306, //数据库服务器端口
  7. pool: {
  8. max: 5,
  9. min: 0,
  10. idle: 10000
  11. },
  12. });
  13. module.exports = Mysql;

然后根据数据库图,依次创建对应的Model

这里以user.js为示例 多带带说下:

</>复制代码

  1. /**
  2. * User 用户表
  3. */
  4. var Sequelize = require("sequelize");//引入sequelize
  5. var Mysql = require("./mysql");//引入mysql实例化
  6. //定义User用户表
  7. var User = Mysql.define("user", {
  8. uuid: {//使用uuid 而不使用
  9. type: Sequelize.UUID,//设置类型
  10. allowNull: false,//是否允许为空
  11. primaryKey: true,//主键
  12. defaultValue: Sequelize.UUIDV1,//默认值
  13. }, //uuid
  14. email: { //邮箱
  15. type: Sequelize.STRING,
  16. allowNull: false,
  17. unique: true, //唯一
  18. validate: {//设置验证条件
  19. isEmail: true,// 检测邮箱格式 (foo@bar.com)
  20. },
  21. },
  22. password: { //密码
  23. type: Sequelize.STRING,
  24. allowNull: false,
  25. },
  26. state: { //状态 0未激活邮箱、1已激活邮箱
  27. type: Sequelize.STRING(2),//限制字符个数
  28. defaultValue: "0", //默认值
  29. },
  30. }, {
  31. freezeTableName: true, //开启自定义表名
  32. tableName: "User",//表名字
  33. timestamps: true, // 添加时间戳属性 (updatedAt, createdAt)
  34. createdAt: "createDate",// 将createdAt字段改个名
  35. updatedAt: "updateDate",// 将updatedAt字段改个名
  36. indexes: [{ // 索引
  37. type: "UNIQUE", //UNIQUE、 FULLTEXT 或 SPATIAL之一
  38. method: "BTREE", //BTREE 或 HASH
  39. unique: true, //唯一 //设置索引是否唯一,设置后会自动触发UNIQUE设置//true:索引列的所有值都只能出现一次,即必须唯一
  40. fields: ["uuid"], //建立索引的字段数组。每个字段可以是一个字段名,sequelize 对象 (如 sequelize.fn),或一个包含:attribute (字段名)、length (创建前缀字符数)、order (列排序方向)、collate (较验的字段集合 (排序))
  41. }],
  42. comment:"User Table",//数据库表描述
  43. });
  44. module.exports = User;//导出

表都写完后,新建index.js

</>复制代码

  1. **
  2. * 数据库表关系建立
  3. */
  4. var Mysql = require("./mysql");
  5. //表
  6. var AdminUser = require("./adminUser");//管理员表
  7. var User = require("./user");//用户表
  8. var UserInfo = require("./userInfo");//用户信息表
  9. var Article = require("./article");//文章表
  10. var Category = require("./category");//文章类别表
  11. var Attachment = require("./attachment");//文章附件表
  12. /**
  13. * 关系建立
  14. */
  15. //用户-用户资料
  16. User.hasOne(UserInfo); //1:1
  17. //用户-文章
  18. User.hasMany(Article); //1:N
  19. Article.belongsTo(User); //1:1
  20. //文章-分类 (定义中间表ArticleCategory 实现多对多)
  21. Article.belongsToMany(Category,{through: "ArticleCategory"}); //N:N
  22. Category.belongsToMany(Article,{through: "ArticleCategory"}); //N:N
  23. //基于sequelize自动创建表//【!!注意 首次执行完请注释掉该段代码 !!】
  24. Mysql.sync({
  25. force: true,//是否清空数据库表
  26. }).then(function() {
  27. console.log("ok");
  28. });
  29. module.exports = {
  30. AdminUser: AdminUser,
  31. User: User,
  32. UserInfo: UserInfo,
  33. Article: Article,
  34. Category: Category,
  35. Attachment: Attachment,
  36. };

好。到这里,咱们咱们打开

blogNodejs/app.js 写入以下代码

</>复制代码

  1. /**
  2. * 主入口启动文件
  3. * add by wwj
  4. * 2017-08-24 15:01:48
  5. */
  6. var express = require("express"); //web 框架
  7. var logger = require("morgan"); //开发模式下log
  8. var bodyParser = require("body-parser"); //json
  9. var path = require("path"); //路径
  10. var config = require("config-lite"); //读取配置文件
  11. var winston = require("winston"); //日志
  12. var expressWinston = require("express-winston"); //基于 winston 的用于 express 的日志中间件
  13. var models = require("./models"); //临时添加 为了生成数据库表,后面写到Controllers里面
  14. //实例化express
  15. var app = express();
  16. // 设置模板目录
  17. app.set("views", path.join(__dirname, "views"));
  18. // 设置模板引擎为 ejs
  19. app.set("view engine", "ejs");
  20. // log
  21. app.use(logger("dev"));
  22. //设置json
  23. //格式化JSON的输出
  24. app.set("json spaces", 2);
  25. // parse application/x-www-form-urlencoded
  26. app.use(bodyParser.urlencoded({
  27. extended: false
  28. }));
  29. // parse application/json
  30. app.use(bodyParser.json());
  31. // 设置静态文件目录
  32. app.use(express.static(path.join(__dirname, "public"))); //注意:中间件的加载顺序很重要。如上面设置静态文件目录的中间件应该放到 routes(app) 之前加载,这样静态文件的请求就不会落到业务逻辑的路由里;
  33. //错误请求的日志
  34. app.use(expressWinston.errorLogger({
  35. transports: [
  36. new winston.transports.Console({
  37. json: true,
  38. colorize: true
  39. }),
  40. new winston.transports.File({
  41. filename: "logs/error.log"
  42. })
  43. ]
  44. }));
  45. // error handler
  46. app.use(function(err, req, res, next) {
  47. // set locals, only providing error in development
  48. res.locals.message = err.message;
  49. res.locals.error = req.app.get("env") === "development" ? err : {};
  50. // render the error page
  51. res.status(err.status || 500);
  52. res.render("error");
  53. });
  54. //app
  55. module.exports = app;

执行一下

</>复制代码

  1. npm run dev

然后去mysql 下看看是否创建成功了(右击“表”-刷新)

到这里,咱们的数据库已经ok啦

下面学习了解些业务逻辑写法

</>复制代码

  1. // 字段类型
  2. // STRING
  3. // CHAR
  4. // TEXT
  5. // INTEGER :A 32 bit integer.
  6. // BIGINT :A 64 bit integer.
  7. // FLOAT
  8. // REAL
  9. // DOUBLE
  10. // DECIMAL
  11. // BOOLEAN
  12. // TIME
  13. // DATE
  14. // BLOB
  15. //where
  16. $and: {a: 5} // AND (a = 5)
  17. $or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6)
  18. $gt: 6, // > 6
  19. $gte: 6, // >= 6
  20. $lt: 10, // < 10
  21. $lte: 10, // <= 10
  22. $ne: 20, // != 20
  23. $not: true, // IS NOT TRUE
  24. $between: [6, 10], // BETWEEN 6 AND 10
  25. $notBetween: [11, 15], // NOT BETWEEN 11 AND 15
  26. $in: [1, 2], // IN [1, 2]
  27. $notIn: [1, 2], // NOT IN [1, 2]
  28. $like: "%hat", // LIKE "%hat"
  29. $notLike: "%hat" // NOT LIKE "%hat"
  30. $iLike: "%hat" // ILIKE "%hat" (case insensitive) (PG only)
  31. $notILike: "%hat" // NOT ILIKE "%hat" (PG only)
  32. $like: { $any: ["cat", "hat"]}
  33. // LIKE ANY ARRAY["cat", "hat"] - also works for iLike and notLike
  34. $overlap: [1, 2] // && [1, 2] (PG array overlap operator)
  35. $contains: [1, 2] // @> [1, 2] (PG array contains operator)
  36. $contained: [1, 2] // <@ [1, 2] (PG array contained by operator)
  37. $any: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only)
  38. $col: "user.organization_id" // = "user"."organization_id", with dialect specific column identifiers, PG in this example
  39. {
  40. rank: {
  41. $or: {
  42. $lt: 1000,
  43. $eq: null
  44. }
  45. }
  46. }
  47. // rank < 1000 OR rank IS NULL
  48. {
  49. createdAt: {
  50. $lt: new Date(),
  51. $gt: new Date(new Date() - 24 * 60 * 60 * 1000)
  52. }
  53. }
  54. // createdAt < [timestamp] AND createdAt > [timestamp]
  55. {
  56. $or: [
  57. {
  58. title: {
  59. $like: "Boat%"
  60. }
  61. },
  62. {
  63. description: {
  64. $like: "%boat%"
  65. }
  66. }
  67. ]
  68. }
  69. // title LIKE "Boat%" OR description LIKE "%boat%"

</>复制代码

  1. CURD
  2. create
  3. result.dataValues;
  4. ========================
  5. update
  6. result [1];
  7. ========================
  8. find - 从数据库中查找一个指定元素
  9. - findById 按已知id查找
  10. - findOne 按属性查找
  11. result.dataValues
  12. ========================
  13. findOrCreate - 从数据库中查找一个指定元素如果不存在则创建记录
  14. ========================
  15. findAndCountAll - 从数据库中查找多个元素,返回数据与记录总数
  16. count - 整数,匹配到的总记录数
  17. rows - 对象数据,通过 limit 和 offset匹配的当前页数据
  18. { count: 0, rows: [] }
  19. findAndCountAll同样支持使用include包含,使用包含时只有将required设置为true才会添加到count部分:
  20. User.findAndCountAll({
  21. include: [
  22. { model: Profile, required: true}
  23. ],
  24. limit: 3
  25. });
  26. 使用include时,两个模型之间应该存在主/外键关系,如果不存在就应该在include中手工建立连接。
  27. 在上面的示例中,为Profile设置了required,所以在查询时会使用INNER JOIN内连接。
  28. ========================
  29. findAll - 从数据库中查找多个元素
  30. // 查询时使用字符串替换
  31. Project.findAll({ where: ["id > ?", 25] }).then(function(projects) {
  32. // projects 是一个包含 Project 实例的数组,各实例的id 大于25
  33. })
  34. ========================
  35. count - 统计数据库中的元素数
  36. max - 查找指定表中最大值
  37. min - 查找指定表中最小值
  38. sum - 对指定属性求和
  39. ========================
  40. destroy
  41. result
项目实战(提前了解,后面可以再学到controller那一层的时候看代码学习使用) 新增

更新

查询单个

查询全部 模糊查询、分页、排序

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/104081.html

相关文章

  • 4.7 multer文件上传-博客后端Api-NodeJs+Express+Mysql实战

    摘要:给上传文件重命名,获取添加后缀名允许最大层文件上传国际化工具类房源附件文件服务文件上传文件文件名相对路径对应值文件大小后面写到前端的时候再说怎么调用 multer文件上传 https://github.com/expressjs/... 在博客系统中会涉及到文件上传,这时候需要用到 multer文件上传 model层 /** * Attachment附件表 * @type {[t...

    android_c 评论0 收藏0
  • 4.1 开发环境目录结构配置文件功能梳理-博客后端Api-NodeJs+Express+Mys

    摘要:从本章开始,正式学习如何使用搭建一个博客。但通常我们都会有许多环境,如本地开发环境测试环境和线上环境等,不同的环境的配置不同,我们不可能每次部署时都要去修改引用或者。会根据环境变量的不同从当前执行进程目录下的目录加载不同的配置文件。 从本章开始,正式学习如何使用 Nodejs + Express + Mysql 搭建一个博客。 开发环境 首先说下开发环境安装的核心依赖版本: Node....

    DevWiki 评论0 收藏0
  • NodeJs+Express+Mysql + Vuejs 项目实战 - 大纲

    摘要:多一个技能多一条出路,祝你在自学道路上越走越好,掌握自己的核心技能,不只是优秀,还要成为不可替代的人 NodeJs+Express+Mysql + Vuejs 项目实战 最近准备写一系列文章,全面讲述如何基于NodeJs + Express + Mysql + Vuejs 从零开发前后端完全分离项目; 文笔及技术可能在某些方面欠佳,请您指正,共同学习进步 前端:Vuejs全家桶 后端:...

    noONE 评论0 收藏0
  • 4.3 路由设计/RESTful API-博客后端Api-NodeJs+Express+Mysql

    摘要:路由设计路由设计以用户注册为例介绍如何闭环用户注册开发注意点使用邮箱注册验证邮箱是否注册目前真实开发业务大部分都是手机号注册,这块由于没有购买短信服务首先,在文件夹下新建上图中对应真实业务逻辑现附上业务实现代码加密国际化工具类用户服务 路由设计 路由设计 以用户注册为例介绍如何闭环用户注册开发注意点:(1)使用邮箱注册(2)验证邮箱是否注册 【目前真实开发业务大部分都是手机号注册,这块...

    1fe1se 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<