Sequelize不创建多对多连接表

时间:2016-05-23 16:58:17

标签: many-to-many sequelize.js

当我启动服务器时,在建立数据库连接后不久我就这样做了:

var tool = require("./tool"); //created with Sequelize.define()
var requirement = require("./requirement"); //created with Sequelize.define()

tool.belongsToMany(requirement, {through: "toolRequirements"});
requirement.belongsToMany(tool, {through: "toolRequirements"});

tool.sync();
requirement.sync();

我希望看到正在创建连接表,但它并不存在。我错过了什么?

Executing (default): CREATE TABLE IF NOT EXISTS `requirements` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);
Executing (default): CREATE TABLE IF NOT EXISTS `tools` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255) NOT NULL, `idCode` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);
Executing (default): PRAGMA INDEX_LIST(`requirements`)
Executing (default): PRAGMA INDEX_LIST(`tools`)

它表示in the documentation表是为我创建的。我不应该自己手动创建一个。

我正在使用:

1 个答案:

答案 0 :(得分:6)

似乎不是在每个模型上调用.sync(),而是应该只调用sequelize.sync()一次。

这样做:

var tool = require("./tool"); //created with Sequelize.define()
var requirement = require("./requirement"); //created with Sequelize.define()

tool.belongsToMany(requirement, {through: "toolRequirements"});
requirement.belongsToMany(tool, {through: "toolRequirements"});

sequelize.sync();

//DO NOT tool.sync();
//DO NOT requirement.sync();

以下是我在项目中使用它的示例:link