文章目录

node.js的orm框架也用了几款,像之前的orm,orm2等,但是感觉维护和更新速度跟不上,而且BUG太多,不支持最新的Nodejs 0.12的generator特性。

后来发现了sequelize令我眼前一亮,完善的API和详细的文档资料而且现在发现的BUG屈指可数,就算有都会很快修复。

使用sql数据库最基本的ORM映射之外肯定还有关系映射,sequelize能让你使用最少的代码实现最复杂的映射

比如:
一个文章model和一个文章分类model的关系描述。

Article.js 文章Model
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var Article = sequelize.define("info",{
id: {type: Sequelize.UUIDV4, primaryKey: true, defaultValue: Sequelize.UUIDV4},
category_id: {type:Sequelize.STRING(36),allowNull:false},
title:{type:Sequelize.STRING(200),allowNull:false},
content:{type:Sequelize.TEXT,allowNull:false},
imgurl:{type:Sequelize.STRING(100)},
remark:{type:Sequelize.STRING(200)},
ispublished:{type:Sequelize.BOOLEAN,allowNull:false},
creator_id:{type:Sequelize.STRING(36),allowNull:false},
createtime:{type:Sequelize.DATE,defaultValue:Sequelize.now},
publishtime:{type:Sequelize.DATE,defaultValue:Sequelize.now},
publisher_id:{type:Sequelize.STRING(36),allowNull:false}
});

Article.belongsTo(Category,{as:'Category',foreignKey:'category_id'});
Article.belongsTo(Staff,{as:'Creator',foreignKey:'creator_id'});
Article.belongsTo(Staff,{as:'Publisher',foreignKey:'publisher_id'});

Category.hasMany(Article,{as:'Articles',foreignKey:'category_id'});
Category.belongsTo(Staff,{as:'Creator',foreignKey:'creator_id'});
Category.belongsTo(Staff,{as:'Publisher',foreignKey:'publisher_id'});

module.exports = Article;

分类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var Category = sequelize.define("category",{
id: {type: Sequelize.UUIDV4, primaryKey: true, defaultValue: Sequelize.UUIDV4},
name: {type:Sequelize.STRING(50),allowNull:false},
bigimgurl:{type:Sequelize.STRING(200)},
smallimgurl:{type:Sequelize.STRING(200)},
platecode:{type:Sequelize.INTEGER},
remark:{type:Sequelize.STRING(200)},
ispublished:{type:Sequelize.BOOLEAN,allowNull:false},
creator_id:{type:Sequelize.STRING(36),allowNull:false},
createtime:{type:Sequelize.DATE,defaultValue:Sequelize.now},
publishtime:{type:Sequelize.DATE,defaultValue:Sequelize.now},
publisher_id:{type:Sequelize.STRING(36),allowNull:false}
});

module.exports = Category;

Article.belongsTo(Category,{as:'Category',foreignKey:'category_id'});表示文章属于一个分类,也就是一对一关系。使用‘foreignKey’来标识外键。
Category.hasMany(Article,{as:'Articles',foreignKey:'category_id'}); 表示一个分类下有多个文章(当然也可以在‘Article’里面使用belongsToMany来表示)

最新版的sequelize多对多关系双方都是 hasMany 或belongsToMany来表示sequelize会抛出红色警告,建议双向使用’belongsToMany’即可。

上面的关系描述我为什么都卸载Article.js里面呢?是因为requere加载顺序原因,如果分开写,后加在的model会未初始化完成! 所以要么把所有model写到一个文件(这份方法显然无法接受),所以这种就把关系描述全部丢到关系中个人认为最常用最容易注意到的Model中。

此文是本站原创,转载请标注作者和链接出处!