多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 初步搭建数据库的模型 基础包 > mysql2 > sequelize 前言: 在连接数据库的时候发现sequelize可以搭建数据库的model。特别写下一遍记录文,不过也踩了不少的坑 目录结构: ~~~ app | |---orm | | | |---data //数据库操作逻辑 | | |---index.js | |---db //数据库连接初始化 | | |---index.js | |---model //表的模型 | | |---users // users表 | | | |---index.js | ~~~ model下的user代码: ~~~ let client = require('./../../db/index'); let Sequelize = require('sequelize') let sequelize = client.client let userModel = sequelize.define('users',{ 'USER_ID': { type: Sequelize.INTEGER, allowNull: false, primaryKey: true }, 'USER_NAME': { type: Sequelize.STRING }, 'USER_IPHONE': { type: Sequelize.STRING }, 'USER_MONEY': { type: Sequelize.INTEGER }, 'USER_PASSWORD': { type: Sequelize.STRING } },{ createdAt: false, updatedAt: false }); module.exports.userModel = userModel ~~~ data下面的index代码: ~~~ const Sequelize = require('sequelize'); const db = require('./../db/index'); const userModel = require('./../model/user/index'); exports.findAll = function *(query) { let sql = 'select * from users where user_id = :id'; return yield db.client.query(sql, { replacements: { id: query.id }, type: Sequelize.QueryTypes.SELECT }) } exports.findOne = function *(query) { let data = yield userModel.userModel.findById(query.id); console.log(data.dataValues); return data.dataValues // console.log(query) } ~~~ router里调用业务层逻辑代码: ~~~ /** * Created by Administrator on 2017/8/5. */ const db = require('./../orm/data'); let getArticle = exports.getArticle = function *() { this.body = 'hell word getarticle' } let findAll = exports.findAll = function *() { let query = { id: 1 } let data = yield db.findAll(query); this.body = data } let findOne = exports.findOne = function *() { let query = { id: 1 } let data = yield db.findOne(query); this.body = data } exports.register = function (router) { router.get('/api/getArticle', getArticle) router.get('/api/findAll', findAll) router.get('/api/findOne', findOne) }; ~~~ 坑点: * 可能是自己部不怎么熟悉export的语法问题,export导出后是个对象所以要点client,才能拿到数据库的实例 * 表名会默认添加s,所以填写表名和,新建表的时候需要注意。当然也可以自己编写configuration来指定表名tableName,具体可以参考下面这条连接。[表名修改](https://itbilu.com/nodejs/npm/V1PExztfb.html#definition-configuration) * 还是需要自己引入sequelize来确认类型。目前我也不知道是为啥。