質問編集履歴

1

models/indexの内容を追加

2021/04/17 23:04

投稿

gasuketu
gasuketu

スコア10

test CHANGED
File without changes
test CHANGED
@@ -74,6 +74,86 @@
74
74
 
75
75
  ```
76
76
 
77
+ ```javascript
78
+
79
+ //models/index
80
+
81
+ 'use strict';
82
+
83
+
84
+
85
+ const fs = require('fs');
86
+
87
+ const path = require('path');
88
+
89
+ const Sequelize = require('sequelize');
90
+
91
+ const basename = path.basename(__filename);
92
+
93
+ const env = process.env.NODE_ENV || 'development';
94
+
95
+ const config = require(__dirname + '/../config/config.json')[env];
96
+
97
+ const db = {};
98
+
99
+
100
+
101
+ let sequelize;
102
+
103
+ if (config.use_env_variable) {
104
+
105
+ sequelize = new Sequelize(process.env[config.use_env_variable], config);
106
+
107
+ } else {
108
+
109
+ sequelize = new Sequelize(config.database, config.username, config.password, config);
110
+
111
+ }
112
+
113
+
114
+
115
+ fs
116
+
117
+ .readdirSync(__dirname)
118
+
119
+ .filter(file => {
120
+
121
+ return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
122
+
123
+ })
124
+
125
+ .forEach(file => {
126
+
127
+ const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
128
+
129
+ db[model.name] = model;
130
+
131
+ });
132
+
133
+
134
+
135
+ Object.keys(db).forEach(modelName => {
136
+
137
+ if (db[modelName].associate) {
138
+
139
+ db[modelName].associate(db);
140
+
141
+ }
142
+
143
+ });
144
+
145
+
146
+
147
+ db.sequelize = sequelize;
148
+
149
+ db.Sequelize = Sequelize;
150
+
151
+
152
+
153
+ module.exports = db;
154
+
155
+ ```
156
+
77
157
  ```json
78
158
 
79
159
  //package.json