猿问

sequelize的文档为什么建议用sequelize.import()的方式将model来分成模块

koa或express中用sequelize一般都要把一个个model放到单文件,官方文档给了一个奇怪的做法,它自己提供了个import的方法,然后让model单文件导出一个函数


// in your server file - e.g. app.js

const Project = sequelize.import(__dirname + "/path/to/models/project")


// The model definition is done in /path/to/models/project.js

// As you might notice, the DataTypes are the very same as explained above

module.exports = (sequelize, DataTypes) => {

  return sequelize.define("project", {

    name: DataTypes.STRING,

    description: DataTypes.TEXT

  })

}

https://github.com/sequelize/...
这个官方样例更详细

但是我觉得我这样写,模块化会更舒服一点

// sequelize.js

import Sequelize from 'sequelize'

const sequelize = new Sequelize({

    ...

})

export default sequelize


// model/modelA.js

import Sequelize from 'sequelize'

import sequelize from './sequelize'

export default sequelize.define("project", {

    name: Sequelize.STRING,

    description: Sequelize.TEXT

})



// in route

import modelA from 'path/to/model/modelA'


// or by using model/index.js

import { modelA } from 'path/to/model'

不知道我的想法会有什么问题


慕无忌1623718
浏览 2400回答 1
1回答

慕的地10843

解决nodejs require module时循环引用会导致undefined的问题这个一般在定义关联的时候会用。目前我的做法是把所有model的关联放到一个js去做import { Authorize, AuthorizeAttributes, AuthorizeInstance } from './authorize';import { Comment, CommentAttributes, CommentInstance } from './comment';import { Hit, HitAttributes, HitInstance } from './hit';import { Moneylog, MoneylogAction, MoneylogAttributes, MoneylogInstance } from './moneylog';import { Order, OrderAttributes, OrderInstance } from './order';import { Post, PostAttributes, PostContentType, PostInstance } from './post';import { Poundage, PoundageAttributes, PoundageInstance } from './poundage';import { User, UserAttributes, UserInstance } from './user';import { Withdrawal, WithdrawalAttributes, WithdrawalInstance } from './withdrawal';Comment.belongsTo(Post, { foreignKey: 'post_id', as: 'post' });Comment.belongsTo(User, { foreignKey: 'user_id', as: 'user' });Order.belongsTo(User, { foreignKey: 'user_id', as: 'user' });Order.belongsTo(Post, { foreignKey: 'post_id', as: 'post' });Post.belongsTo(User, { foreignKey: 'user_id', as: 'user' });Post.hasMany(Comment, { foreignKey: 'post_id', as: 'commentList' });User.hasMany(Post, { foreignKey: 'user_id', as: 'posts' });User.hasMany(Order, { foreignKey: 'user_id', as: 'orders' });User.hasMany(Comment, { foreignKey: 'user_id', as: 'comment' });
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答