Knex.js:创建表并插入数据 [英] Knex.js: Create table and insert data

查看:662
本文介绍了Knex.js:创建表并插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我有一个像这样的Knex.js脚本:

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();
    });
};

当前会创建一个表格.

如何在此脚本中添加后续的插入语句?

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?

不幸的是,我没有在Knex.js文档中找到任何创建+插入的 complete 示例.

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

推荐答案

然后方法返回 Promise ,您可以在创建了桌子.例如:

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

这篇关于Knex.js:创建表并插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆