Knex.js:创build表并插入数据
鉴于我有这样一个Knex.js脚本:
exports.up = function(knex, Promise) { return knex.schema.createTable('persons', function(table) { table.increments('id').primary(); table.string('name').notNullable(); }); };
当前创build一个表。
如何将后续插入语句添加到此脚本?
我想要做的是添加一个这样的行(或类似):
knex.insert({id: 1, name: 'Test'}).into('persons')
我不确定我是否理解这种基于承诺的方法是如何工作的。 我应该写插入语句的另一个脚本? 或者我可以以某种方式追加到我现有的脚本?
不幸的是,我没有在Knex.js文档中find任何完整的create + insert的例子。
为什么不使用Promise 然后你可以做的方法例如:
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") ]); };
好,现在我明白了。
编辑:不,我没有。 看到fareed namrouti的答案是真正的解决scheme。
Knex似乎区分“模式迁移脚本”和“常规SQL查询”,后者包括INSERT语句。
- 模式迁移脚本在专用的迁移脚本文件中组织,并使用例如
knex.migrate.latest()
- 从任何节点脚本调用常规语句
因此,我必须将INSERT语句放在常规的Node脚本中, 而不是在迁移脚本的exports.up
函数中。
尽pipe如此,我仍然无法在文档中明确指出这一点。