型号定义
本页内容已移至 模型基础。
¥The contents of this page were moved to Model Basics.
唯一的例外是 sequelize.import
上的指南,该指南已被弃用并已从文档中删除。但是,如果你确实需要它,它就保存在这里。
¥The only exception is the guide on sequelize.import
, which is deprecated and was removed from the docs. However, if you really need it, it was kept here.
已弃用:sequelize.import
¥Deprecated: sequelize.import
注意:你不应该使用
sequelize.import
。请仅使用import
、import()
或require
。¥Note: You should not use
sequelize.import
. Please just useimport
,import()
, orrequire
instead.保留此文档是为了以防万一你确实需要维护使用它的旧代码。
¥This documentation has been kept just in case you really need to maintain old code that uses it.
sequelize.import
只能加载 CommonJS 文件,不能加载 ecmascript modules
。如果需要加载 ecmascript 模块,请使用原生 import
。
¥sequelize.import
can only load CommonJS files, and is not capable of loading ecmascript modules
. Use native import
if you need to load ecmascript modules.
你可以使用 sequelize.import
方法将模型定义存储在单个文件中。返回的对象与导入文件的函数中定义的完全相同。导入会被缓存,就像 require
一样,因此如果多次导入文件,你不会遇到麻烦。
¥You can store your model definitions in a single file using the sequelize.import
method. The returned object is exactly the same as defined in the imported file's function. The import is cached, just like require
, so you won't run into trouble if importing a file more than once.
// 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
方法还可以接受回调作为参数。
¥The import
method can also accept a callback as an argument.
sequelize.import('project', (sequelize, DataTypes) => {
return sequelize.define('project', {
name: DataTypes.STRING,
description: DataTypes.TEXT,
});
});
例如,当 Error: Cannot find module
被抛出时,即使 /path/to/models/project
看起来是正确的,这种额外的功能也很有用。某些框架(例如 Meteor)会重载 require
,并且可能会引发错误,例如:
¥This extra capability is useful when, for example, Error: Cannot find module
is thrown even though /path/to/models/project
seems to be correct. Some frameworks, such as Meteor, overload require
, and might raise an error such as:
Error: Cannot find module '/home/you/meteorApp/.meteor/local/build/programs/server/app/path/to/models/project.js'
这可以通过传入 Meteor 的 require
版本来解决:
¥This can be worked around by passing in Meteor's version of 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'));