鉴于我有一个像这样的Knex.js脚本:
exports.up = function(knex, Promise) {
return knex.schema.createTable('persons', function(table) {
table.increments('id').primary();
table.string('name').notNullable();
});
};
Run Code Online (Sandbox Code Playgroud)
目前创建一个表.
如何将后续插入语句添加到此脚本?
我想要做的是添加像这样(或类似)的行:
knex.insert({id: 1, name: 'Test'}).into('persons')
Run Code Online (Sandbox Code Playgroud)
我不确定我理解这种基于承诺的方法是如何工作的.我应该用insert语句编写另一个脚本吗?或者我可以以某种方式将它们附加到我现有的脚本中吗?
不幸的是,我在Knex.js文档中找不到任何完整的create + insert示例.
Far*_*uti 19
为什么不使用Promise then方法,例如:
exports.up = function (knex, Promise) {
return Promise.all([
knex.schema.createTableIfNotExists("payment_paypal_status", function (table) {
table.increments(); // integer id
// name
table.string('name');
//description
table.string('description');
}).then(function () {
return knex("payment_paypal_status").insert([
{name: "A", description: "A"},
{name: "B", description: "BB"},
{name: "C", description: "CCC"},
{name: "D", description: "DDDD"}
]);
}
),
]);
};
exports.down = function (knex, Promise) {
return Promise.all([
knex.schema.dropTableIfExists("payment_paypal_status")
]);
};
Run Code Online (Sandbox Code Playgroud)
使用现代 Javascript 的await/async关键字,你可以这样做:
exports.up = async function(knex) {
await knex.schema.createTable('persons', function(table) {
table.increments('id').primary();
table.string('name').notNullable();
});
// You could replace "return" by "await" here if you wish.
return knex.insert({id: 1, name: 'Test'}).into('persons');
};
Run Code Online (Sandbox Code Playgroud)
基本上是一样的,除了使用await/async代替then.