关于node.js:nodejs使用Sequelize框架操作数据库

40次阅读

共计 1548 个字符,预计需要花费 4 分钟才能阅读完成。

sequelize.define

应用该办法能够定义 model,例子如下:

const Sequelize = require('sequelize');

var sequelize = new Sequelize(config.database, config.username, config.password, {
    host: config.host,
    dialect: 'mysql',
    pool: {
        max: 5,
        min: 0,
        idle: 30000
    }
});

var Website = sequelize.define('website', {
    id: {
        type: Sequelize.BIGINT,
        primaryKey: true,
        autoIncrement: true
    },
    url: Sequelize.STRING(255),
    title: Sequelize.STRING(255),
    status: Sequelize.INTEGER,
    delete_mark: Sequelize.BOOLEAN
}, {timestamps: false});

该办法传入的第一个参数是数据表的复数模式,怎么了解呢?例如这里传入的是 website 其实是模型名,数据表默认是 websites 这样的复数模式,这种约定我在 Laravel 中也碰见过,
也就是常说的,约定大于定义,也就是说,如果咱们都依照约定的标准去开发,那么效率其实比从新定义,要高很多。
那么,定义好了模型,该怎么进行应用呢?

(async () => {
    let demo = await Website.create({
       url:'http://www.xxxx.com/',
       title:'demo'
    });
    console.log(demo);
})();

继承 Model

const {Sequelize, DataTypes, Model} = require('sequelize');
const config = require('../config');

const sequelize = new Sequelize(config.database, config.username, config.password, {
    host: config.host,
    dialect: 'mysql',
    pool: {
        max: 5,
        min: 0,
        idle: 30000
    }
});

/**
 * @author chaojilaji
 * 数据表 websites 的关系对象映射
 */
class WebSite extends Model {

}

WebSite.init({
    id: {
        type: Sequelize.BIGINT,
        primaryKey: true,
        autoIncrement: true
    },
    url: Sequelize.STRING(255),
    title: Sequelize.STRING(255),
    status: Sequelize.INTEGER,
    delete_mark: Sequelize.BOOLEAN
}, {
    sequelize,
    modelName: 'Website',
    timestamps:false
});

(async () => {await sequelize.sync();
    let x = await WebSite.create({
        url: 'http://www.xxxxxxxx.com/',
        title: 'demo2'
    });
    console.log(x);
})();

module.exports = WebSite;

我比拟举荐应用继承 Model 这种形式,通过创立一个 class,这样能够应用 model.exports= 模块名的形式,将该模型封装起来。供别的中央应用,只须要 require 进去即可。

具体如何对数据表进行操作,就比较简单了,只须要参考 API 即可。sequelize 文档地址

炒鸡辣鸡原创文章,转载请注明起源

正文完
 0