功能梳理完了以后,咱們就可以開始數(shù)據(jù)庫表設(shè)計了:
數(shù)據(jù)庫表圖:
首先打開Navicat Premium 創(chuàng)建數(shù)據(jù)庫 blog
配置如下:
課前學習:
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、關(guān)于“時間”的一次探索
https://segmentfault.com/a/11...
在blogNodejs/models 下
首先新建 mysql.js 進行mysql連接配置(基于Sequelize)
var config = require("config-lite");//引入靈活配置文件 var Sequelize = require("sequelize");.//引入Sequelize var Mysql = new Sequelize(config.mysql.database, config.mysql.user, config.mysql.password, { host: config.mysql.host, //數(shù)據(jù)庫服務(wù)器ip dialect: "mysql", //數(shù)據(jù)庫使用mysql port: 3306, //數(shù)據(jù)庫服務(wù)器端口 pool: { max: 5, min: 0, idle: 10000 }, }); module.exports = Mysql;
然后根據(jù)數(shù)據(jù)庫圖,依次創(chuàng)建對應(yīng)的Model
這里以user.js為示例 多帶帶說下:
/** * User 用戶表 */ var Sequelize = require("sequelize");//引入sequelize var Mysql = require("./mysql");//引入mysql實例化 //定義User用戶表 var User = Mysql.define("user", { uuid: {//使用uuid 而不使用 type: Sequelize.UUID,//設(shè)置類型 allowNull: false,//是否允許為空 primaryKey: true,//主鍵 defaultValue: Sequelize.UUIDV1,//默認值 }, //uuid email: { //郵箱 type: Sequelize.STRING, allowNull: false, unique: true, //唯一 validate: {//設(shè)置驗證條件 isEmail: true,// 檢測郵箱格式 ([email protected]) }, }, password: { //密碼 type: Sequelize.STRING, allowNull: false, }, state: { //狀態(tài) 0未激活郵箱、1已激活郵箱 type: Sequelize.STRING(2),//限制字符個數(shù) defaultValue: "0", //默認值 }, }, { freezeTableName: true, //開啟自定義表名 tableName: "User",//表名字 timestamps: true, // 添加時間戳屬性 (updatedAt, createdAt) createdAt: "createDate",// 將createdAt字段改個名 updatedAt: "updateDate",// 將updatedAt字段改個名 indexes: [{ // 索引 type: "UNIQUE", //UNIQUE、 FULLTEXT 或 SPATIAL之一 method: "BTREE", //BTREE 或 HASH unique: true, //唯一 //設(shè)置索引是否唯一,設(shè)置后會自動觸發(fā)UNIQUE設(shè)置//true:索引列的所有值都只能出現(xiàn)一次,即必須唯一 fields: ["uuid"], //建立索引的字段數(shù)組。每個字段可以是一個字段名,sequelize 對象 (如 sequelize.fn),或一個包含:attribute (字段名)、length (創(chuàng)建前綴字符數(shù))、order (列排序方向)、collate (較驗的字段集合 (排序)) }], comment:"User Table",//數(shù)據(jù)庫表描述 }); module.exports = User;//導(dǎo)出
表都寫完后,新建index.js
** * 數(shù)據(jù)庫表關(guān)系建立 */ var Mysql = require("./mysql"); //表 var AdminUser = require("./adminUser");//管理員表 var User = require("./user");//用戶表 var UserInfo = require("./userInfo");//用戶信息表 var Article = require("./article");//文章表 var Category = require("./category");//文章類別表 var Attachment = require("./attachment");//文章附件表 /** * 關(guān)系建立 */ //用戶-用戶資料 User.hasOne(UserInfo); //1:1 //用戶-文章 User.hasMany(Article); //1:N Article.belongsTo(User); //1:1 //文章-分類 (定義中間表ArticleCategory 實現(xiàn)多對多) Article.belongsToMany(Category,{through: "ArticleCategory"}); //N:N Category.belongsToMany(Article,{through: "ArticleCategory"}); //N:N //基于sequelize自動創(chuàng)建表//【?。∽⒁?首次執(zhí)行完請注釋掉該段代碼 ?。 ?Mysql.sync({ force: true,//是否清空數(shù)據(jù)庫表 }).then(function() { console.log("ok"); }); module.exports = { AdminUser: AdminUser, User: User, UserInfo: UserInfo, Article: Article, Category: Category, Attachment: Attachment, };
好。到這里,咱們咱們打開
blogNodejs/app.js 寫入以下代碼
/** * 主入口啟動文件 * add by wwj * 2017-08-24 15:01:48 */ var express = require("express"); //web 框架 var logger = require("morgan"); //開發(fā)模式下log var bodyParser = require("body-parser"); //json var path = require("path"); //路徑 var config = require("config-lite"); //讀取配置文件 var winston = require("winston"); //日志 var expressWinston = require("express-winston"); //基于 winston 的用于 express 的日志中間件 var models = require("./models"); //臨時添加 為了生成數(shù)據(jù)庫表,后面寫到Controllers里面 //實例化express var app = express(); // 設(shè)置模板目錄 app.set("views", path.join(__dirname, "views")); // 設(shè)置模板引擎為 ejs app.set("view engine", "ejs"); // log app.use(logger("dev")); //設(shè)置json //格式化JSON的輸出 app.set("json spaces", 2); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); // 設(shè)置靜態(tài)文件目錄 app.use(express.static(path.join(__dirname, "public"))); //注意:中間件的加載順序很重要。如上面設(shè)置靜態(tài)文件目錄的中間件應(yīng)該放到 routes(app) 之前加載,這樣靜態(tài)文件的請求就不會落到業(yè)務(wù)邏輯的路由里; //錯誤請求的日志 app.use(expressWinston.errorLogger({ transports: [ new winston.transports.Console({ json: true, colorize: true }), new winston.transports.File({ filename: "logs/error.log" }) ] })); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? err : {}; // render the error page res.status(err.status || 500); res.render("error"); }); //app module.exports = app;
執(zhí)行一下
npm run dev
然后去mysql 下看看是否創(chuàng)建成功了(右擊“表”-刷新)
到這里,咱們的數(shù)據(jù)庫已經(jīng)ok啦
下面學習了解些業(yè)務(wù)邏輯寫法
// 字段類型 // STRING // CHAR // TEXT // INTEGER :A 32 bit integer. // BIGINT :A 64 bit integer. // FLOAT // REAL // DOUBLE // DECIMAL // BOOLEAN // TIME // DATE // BLOB //where $and: {a: 5} // AND (a = 5) $or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6) $gt: 6, // > 6 $gte: 6, // >= 6 $lt: 10, // < 10 $lte: 10, // <= 10 $ne: 20, // != 20 $not: true, // IS NOT TRUE $between: [6, 10], // BETWEEN 6 AND 10 $notBetween: [11, 15], // NOT BETWEEN 11 AND 15 $in: [1, 2], // IN [1, 2] $notIn: [1, 2], // NOT IN [1, 2] $like: "%hat", // LIKE "%hat" $notLike: "%hat" // NOT LIKE "%hat" $iLike: "%hat" // ILIKE "%hat" (case insensitive) (PG only) $notILike: "%hat" // NOT ILIKE "%hat" (PG only) $like: { $any: ["cat", "hat"]} // LIKE ANY ARRAY["cat", "hat"] - also works for iLike and notLike $overlap: [1, 2] // && [1, 2] (PG array overlap operator) $contains: [1, 2] // @> [1, 2] (PG array contains operator) $contained: [1, 2] // <@ [1, 2] (PG array contained by operator) $any: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only) $col: "user.organization_id" // = "user"."organization_id", with dialect specific column identifiers, PG in this example { rank: { $or: { $lt: 1000, $eq: null } } } // rank < 1000 OR rank IS NULL { createdAt: { $lt: new Date(), $gt: new Date(new Date() - 24 * 60 * 60 * 1000) } } // createdAt < [timestamp] AND createdAt > [timestamp] { $or: [ { title: { $like: "Boat%" } }, { description: { $like: "%boat%" } } ] } // title LIKE "Boat%" OR description LIKE "%boat%"
CURD create result.dataValues; ======================== update result [1]; ======================== find - 從數(shù)據(jù)庫中查找一個指定元素 - findById 按已知id查找 - findOne 按屬性查找 result.dataValues ======================== findOrCreate - 從數(shù)據(jù)庫中查找一個指定元素如果不存在則創(chuàng)建記錄 ======================== findAndCountAll - 從數(shù)據(jù)庫中查找多個元素,返回數(shù)據(jù)與記錄總數(shù) count - 整數(shù),匹配到的總記錄數(shù) rows - 對象數(shù)據(jù),通過 limit 和 offset匹配的當前頁數(shù)據(jù) { count: 0, rows: [] } findAndCountAll同樣支持使用include包含,使用包含時只有將required設(shè)置為true才會添加到count部分: User.findAndCountAll({ include: [ { model: Profile, required: true} ], limit: 3 }); 使用include時,兩個模型之間應(yīng)該存在主/外鍵關(guān)系,如果不存在就應(yīng)該在include中手工建立連接。 在上面的示例中,為Profile設(shè)置了required,所以在查詢時會使用INNER JOIN內(nèi)連接。 ======================== findAll - 從數(shù)據(jù)庫中查找多個元素 // 查詢時使用字符串替換 Project.findAll({ where: ["id > ?", 25] }).then(function(projects) { // projects 是一個包含 Project 實例的數(shù)組,各實例的id 大于25 }) ======================== count - 統(tǒng)計數(shù)據(jù)庫中的元素數(shù) max - 查找指定表中最大值 min - 查找指定表中最小值 sum - 對指定屬性求和 ======================== destroy result項目實戰(zhàn)(提前了解,后面可以再學到controller那一層的時候看代碼學習使用) 新增 更新 查詢單個 查詢?nèi)?模糊查詢、分頁、排序
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/104081.html
摘要:給上傳文件重命名,獲取添加后綴名允許最大層文件上傳國際化工具類房源附件文件服務(wù)文件上傳文件文件名相對路徑對應(yīng)值文件大小后面寫到前端的時候再說怎么調(diào)用 multer文件上傳 https://github.com/expressjs/... 在博客系統(tǒng)中會涉及到文件上傳,這時候需要用到 multer文件上傳 model層 /** * Attachment附件表 * @type {[t...
摘要:從本章開始,正式學習如何使用搭建一個博客。但通常我們都會有許多環(huán)境,如本地開發(fā)環(huán)境測試環(huán)境和線上環(huán)境等,不同的環(huán)境的配置不同,我們不可能每次部署時都要去修改引用或者。會根據(jù)環(huán)境變量的不同從當前執(zhí)行進程目錄下的目錄加載不同的配置文件。 從本章開始,正式學習如何使用 Nodejs + Express + Mysql 搭建一個博客。 開發(fā)環(huán)境 首先說下開發(fā)環(huán)境安裝的核心依賴版本: Node....
摘要:多一個技能多一條出路,祝你在自學道路上越走越好,掌握自己的核心技能,不只是優(yōu)秀,還要成為不可替代的人 NodeJs+Express+Mysql + Vuejs 項目實戰(zhàn) 最近準備寫一系列文章,全面講述如何基于NodeJs + Express + Mysql + Vuejs 從零開發(fā)前后端完全分離項目; 文筆及技術(shù)可能在某些方面欠佳,請您指正,共同學習進步 前端:Vuejs全家桶 后端:...
摘要:路由設(shè)計路由設(shè)計以用戶注冊為例介紹如何閉環(huán)用戶注冊開發(fā)注意點使用郵箱注冊驗證郵箱是否注冊目前真實開發(fā)業(yè)務(wù)大部分都是手機號注冊,這塊由于沒有購買短信服務(wù)首先,在文件夾下新建上圖中對應(yīng)真實業(yè)務(wù)邏輯現(xiàn)附上業(yè)務(wù)實現(xiàn)代碼加密國際化工具類用戶服務(wù) 路由設(shè)計 路由設(shè)計 以用戶注冊為例介紹如何閉環(huán)用戶注冊開發(fā)注意點:(1)使用郵箱注冊(2)驗證郵箱是否注冊 【目前真實開發(fā)業(yè)務(wù)大部分都是手機號注冊,這塊...
閱讀 2022·2021-09-30 09:53
閱讀 1862·2021-09-24 09:48
閱讀 1768·2019-08-30 14:01
閱讀 2183·2019-08-29 18:35
閱讀 1260·2019-08-26 18:27
閱讀 2995·2019-08-26 12:12
閱讀 963·2019-08-23 17:16
閱讀 958·2019-08-23 15:31