Knex.js: Create table and insert data

前提是你 提交于 2020-12-30 08:25:10

问题


Given that I have a Knex.js script like this:

exports.up = function(knex, Promise) {
    return knex.schema.createTable('persons', function(table) {
        table.increments('id').primary();
        table.string('name').notNullable();
    });
};

which currently creates a table.

How do I add subsequent insert statements to this script?

What I want to do is add a line like this (or similar):

knex.insert({id: 1, name: 'Test'}).into('persons')

I'm not sure I understand how this promise-based approach works. Am I supposed to write another script with insert statements? Or can I somehow append them to my existing script?

Unfortunately, I don't find any complete example of create + insert in Knex.js documentation.


回答1:


The then method returns a Promise, which you can use to implement insertion after you have created the table. For example:

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")
    ]);
};


来源:https://stackoverflow.com/questions/35089571/knex-js-create-table-and-insert-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!