egg里怎么完美使用sequelize - CNode技术社区

egg里怎么完美使用sequelize
发布于 8 年前 作者 jiyarong 11372 次浏览 来自 问答

感觉model层写的很混乱,求一个example

module.exports = app => {
 const { DATE, INTEGER, STRING } = app.Sequelize;
 return app.model.define('Post', {
 title: STRING,
 user_id: INTEGER,
 created_at: DATE,
 updated_at: DATE,
 }, {
 classMethods: {
 associate() {
 app.model.Post.belongsTo(app.model.User, { as: 'user' });
 },
 },
 });
};

这种写法,真是写不下去 能否有办法变成类似于这样

Class Post extends Sequelize {
		static ...
}
10 回复

@i5ting 用这一套貌似不能用es6的语法糖 model看起来是这样的

module.exports = app => {
 const { STRING, INTEGER, DATE } = app.Sequelize;
 
 const User = app.model.define('users', {
 username: STRING
 });
 
 User.find = async function(id) {
 const user = await this.findOne({
 where: {
 id: id
 }
 })
 return user || {}
 }
 User.prototype.update_attributes = async function (attributes) {
 const result = await User.update(attributes, {
 where: {
 id: this.id
 }
 })
 return result
 }
 
 
 return User
 };

混乱不堪

@i5ting 看到是generator做的异步控制, 有没有async/await的版本啊

一样的,应该支持 await 的,语法对应着写即可

我看了半天的文档,终于发现了一个可以搞的方法


const Sequelize = require('sequelize');
export default (app) => {
 class article extends Sequelize.Model {
 // coding...
 static foo() {
 console.log('可以调用了')
 }
 }
 article.init({
 id: {
 type: BIGINT,
 primaryKey: true,
 unique: true,
 autoIncrement: true
 },
 title: STRING(64),
 content: TEXT,
 articleID: STRING(64)
 }, { sequelize: app.Sequelize });
 return article
}

1.定义了模型,模型的名字就是表的名字 2.继承了 Sequelize.Model后,就会拥有init静态方法,可供调用 3.init第一个参数就是我们想要的属性(attr),第二个参数的sequelize,要的是Sequelize的实例。 4.依旧不怎么舒服,可以将init方法收敛于类中调用。 5.node层一般用来做BFF比较多,调用底层数据库逻辑工业实践太少,还需要高手来完善一下这些个ORM。。。。。。。。。。。

@215566435 多谢,我等会去试下,感觉egg离所谓的企业级还是任重而道远

@jiyarong 主要是大佬们涉及数据库的东西基本交给java把。node只是中间层

你的问题不在于使用egg里怎么完美使用sequelize, 事实上,你的问题是如何完美使用sequelize.

es6的语法糖只是糖,node js 的肉是原型继承(Prototype inheritance) , 用得好的话彈性和可读性比JAVA要高

在我的koa2-safe-start 1.Relation relation寫在relation.js

global.orm.Feedback.belongsTo(global.orm.User, {
 onDelete: 'cascade',
});

2.Common instance function

//Create Common function
module.exports = {
 last: function() {
 return this.findOne({
 limit: 1,
 where: {
 //your where conditions, or without them if you need ANY entry
 },
 order: [['createdAt', 'DESC']],
 });
 },
};
//And Imported later
 let importedModel = sequelize.import(modelPath);
 for (let methodName of Object.keys(instanceMethods)) {
 importedModel[methodName] = instanceMethods[methodName];
 }
	
	//then now every model can use last

@jiyarong 可以看看 nest.js ,很像spring ,我们基于这个的开源项目: https://github.com/notadd/notadd/tree/next

回到顶部

AltStyle によって変換されたページ (->オリジナル) /