Knex.js:创建表并插入数据

Spu*_*ick 5 node.js knex.js

鉴于我有一个像这样的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)

  • 谢谢,这比我提出的答案更有意义.缺乏Promise的经验让我不知所措. (5认同)
  • 顺便说一句,不需要 Promise.all 包装它。 (5认同)

Joo*_*ink 5

使用现代 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.