模型定義
本頁內容已移至 模型基礎。
唯一的例外是關於 sequelize.import
的指南,該指南已棄用並從文件中移除。但是,如果您真的需要它,它會保留在這裡。
已棄用:sequelize.import
注意:您不應該使用
sequelize.import
。請改用import
、import()
或require
。保留此文件只是為了以防您真的需要維護使用它的舊程式碼。
sequelize.import
只能載入 CommonJS 檔案,無法載入 ecmascript modules
。如果您需要載入 ecmascript 模組,請使用原生的 import
。
您可以使用 sequelize.import
方法將您的模型定義儲存在單一檔案中。傳回的物件與匯入檔案的函數中定義的物件完全相同。匯入會被快取,就像 require
一樣,因此如果您多次匯入檔案,您不會遇到麻煩。
// 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
module.exports = (sequelize, DataTypes) => {
return sequelize.define('project', {
name: DataTypes.STRING,
description: DataTypes.TEXT,
});
};
import
方法也可以接受回呼作為引數。
sequelize.import('project', (sequelize, DataTypes) => {
return sequelize.define('project', {
name: DataTypes.STRING,
description: DataTypes.TEXT,
});
});
當例如即使 /path/to/models/project
看起來是正確的,但仍拋出 Error: Cannot find module
時,此額外功能很有用。某些框架(例如 Meteor)會覆載 require
,並且可能會引發錯誤,例如
Error: Cannot find module '/home/you/meteorApp/.meteor/local/build/programs/server/app/path/to/models/project.js'
可以透過傳入 Meteor 版本的 require
來解決這個問題
// If this fails...
const AuthorModel = db.import('./path/to/models/project');
// Try this instead!
const AuthorModel = db.import('project', require('./path/to/models/project'));