如何基于文件名来构造和访问我的续集模型?
设定:
/models
index.js
User.js
index.js:
import Sequelize from 'sequelize';
const options = {
operatorsAliases,
host: envConfig.host,
dialect: envConfig.dialect
};
const sequelize = new Sequelize(envConfig.database, envConfig.username, envConfig.password, options);
fs.readdirSync(__dirname).filter(file => {
return (file.indexOf('.') !== 0) && (file !== 'index.js') && (file.slice(-3) === '.js');
}).forEach(file => {
let model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
export default db;
User.js
export default (sequelize, dataTypes) => {
return sequelize.define('User', {
email: {
type: dataTypes.STRING,
unique: true,
allowNull: false
},
passwordDigest: {
type: dataTypes.STRING,
allowNull: false
}
});
};
目前,我可以执行此操作来访问.create()
import models from '../models/index';
console.log(models.User.create.toString());
/*
create(values, options) {
options = Utils.cloneDeep(options || {});
return this.build(values, {
isNewRecord: true,
attributes: options.fields,
include: options.include,
raw: options.raw,
silent: options.silent
}).save(options);
}
*/
但我希望能够做到这一点
import { User } from '../models';
User.create({stuff: 1});
答案 0 :(得分:1)
如果您执行export default
,则无法使用解构。
我建议像this一样:
import models from '../models';
const {User} = models;
User.create({stuff: 1});
但您也可以定义模型,如:
const models = (sequelize, dataTypes) => {
return sequelize.define('User', {
email: {
type: dataTypes.STRING,
unique: true,
allowNull: false
},
passwordDigest: {
type: dataTypes.STRING,
allowNull: false
}
});
};
export const User = models.User;
然后根据需要使用它。