在种子文件中创建模型或批量创建承诺
Model create or bulkCreate promise in seed file
我有一些承诺链可以添加数据。如果我在 JavaScript 文件中使用它 "normally",我从 Node.js 开始或以其他方式调用它,它会起作用(或多或少 - 不同的问题)。
但是如果我想在带有 sequelize-cli (sequelize db:seed:all) 的 sequelize 种子文件中使用它,promises 将不起作用。好的,.catch
链中有一个错误,但是 .then
不起作用...
promise 字段都未定义...
我知道我可以使用 bulkInsert,但是如果我 "have to" 使用原始 SQL,为什么还要使用 ORM,尤其是当我在指向 uuid 的表之间有链接时?
我定义了模型,有一个 "normal" 迁移文件,并且想要 "start" 带有种子的数据。我需要单独的东西来使用 create / bulkCreate 承诺吗?
我是否遗漏了文档中的内容?
经过多次尝试,我自己找到了答案:
模型中需要修复的关联:
User.associate = function(models) {
User.belongsToMany(
models.Role, {
through: 'user_role',
}
);
};
和
Role.associate = function(models) {
Role.belongsToMany(
models.User, {
through: 'user_role',
}
);
};
和 m:n table 需要这个:
....
.then(() => {
queryInterface.createTable('user_role', {
userUuid: {
type: Sequelize.UUIDV4,
references: {
model: 'User',
key: 'uuid',
},
allowNull: false,
},
roleUuid: {
type: Sequelize.UUIDV4,
references: {
model: 'Role',
key: 'uuid',
},
allowNull: false,
},
createdAt: { allowNull: false, type: Sequelize.DATE },
updatedAt: { allowNull: false, type: Sequelize.DATE },
});
}).then(() => {
return queryInterface.addConstraint(
'user_role',
['userUuid', 'roleUuid'], {
unique: true,
type: 'primary key',
name: 'userrole_pkey',
}
);
});
将字段重命名为类似于 sequelize 中生成的字段
我有一些承诺链可以添加数据。如果我在 JavaScript 文件中使用它 "normally",我从 Node.js 开始或以其他方式调用它,它会起作用(或多或少 - 不同的问题)。
但是如果我想在带有 sequelize-cli (sequelize db:seed:all) 的 sequelize 种子文件中使用它,promises 将不起作用。好的,.catch
链中有一个错误,但是 .then
不起作用...
promise 字段都未定义...
我知道我可以使用 bulkInsert,但是如果我 "have to" 使用原始 SQL,为什么还要使用 ORM,尤其是当我在指向 uuid 的表之间有链接时?
我定义了模型,有一个 "normal" 迁移文件,并且想要 "start" 带有种子的数据。我需要单独的东西来使用 create / bulkCreate 承诺吗?
我是否遗漏了文档中的内容?
经过多次尝试,我自己找到了答案:
模型中需要修复的关联:
User.associate = function(models) {
User.belongsToMany(
models.Role, {
through: 'user_role',
}
);
};
和
Role.associate = function(models) {
Role.belongsToMany(
models.User, {
through: 'user_role',
}
);
};
和 m:n table 需要这个:
....
.then(() => {
queryInterface.createTable('user_role', {
userUuid: {
type: Sequelize.UUIDV4,
references: {
model: 'User',
key: 'uuid',
},
allowNull: false,
},
roleUuid: {
type: Sequelize.UUIDV4,
references: {
model: 'Role',
key: 'uuid',
},
allowNull: false,
},
createdAt: { allowNull: false, type: Sequelize.DATE },
updatedAt: { allowNull: false, type: Sequelize.DATE },
});
}).then(() => {
return queryInterface.addConstraint(
'user_role',
['userUuid', 'roleUuid'], {
unique: true,
type: 'primary key',
name: 'userrole_pkey',
}
);
});
将字段重命名为类似于 sequelize 中生成的字段