如何使用 Knex 创建 TINYINT 列?

dar*_*nge 3 javascript mysql knex.js

knex 文档中,我只看到创建整数或大整数的选项。

例如,假设我有一个movies包含一rating列的表来存储电影的 5 星评级:

// Migration script

exports.up = knex => {
  return knex.schema
    .createTable('movies', table => {
      table.uuid('id').primary()
      ...
      table.integer('rating') // <-- I want this to be a TINYINT
    })
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在不求助于原始 SQL 查询的情况下做到这一点?

Kei*_*DOG 7

虽然@Jumshud 的答案是一个很好的替代方法,但这里是简短的答案:

table.tinyint('rating');
Run Code Online (Sandbox Code Playgroud)

我深入研究了 Knex 0.21.6 代码,发现了一个可用的方法列表,这些方法甚至没有记录在他们的网站上。在 TableBuilder 文件中knex/lib/schema/tablebuilder.js,是注入到 PseudoClassical 模式原型中的方法列表TableBuilder。为每个columnTypes值创建方法:

// For each of the column methods, create a new "ColumnBuilder" interface,
// push it onto the "allStatements" stack, and then return the interface,
// with which we can add indexes, etc.
each(columnTypes, function (type) {
  TableBuilder.prototype[type] = function () {
    const args = toArray(arguments);
    const builder = this.client.columnBuilder(this, type, args);
    this._statements.push({
      grouping: 'columns',
      builder,
    });
    return builder;
  };
});
Run Code Online (Sandbox Code Playgroud)

columnTypes数组的值是:

// Each of the column types that we can add, we create a new ColumnBuilder
// instance and push it onto the statements array.
const columnTypes = [
  // Numeric
  'tinyint',
  'smallint',
  'mediumint',
  'int',
  'bigint',
  'decimal',
  'float',
  'double',
  'real',
  'bit',
  'boolean',
  'serial',

  // Date / Time
  'date',
  'datetime',
  'timestamp',
  'time',
  'year',

  // String
  'char',
  'varchar',
  'tinytext',
  'tinyText',
  'text',
  'mediumtext',
  'mediumText',
  'longtext',
  'longText',
  'binary',
  'varbinary',
  'tinyblob',
  'tinyBlob',
  'mediumblob',
  'mediumBlob',
  'blob',
  'longblob',
  'longBlob',
  'enum',
  'set',

  // Increments, Aliases, and Additional
  'bool',
  'dateTime',
  'increments',
  'bigincrements',
  'bigIncrements',
  'integer',
  'biginteger',
  'bigInteger',
  'string',
  'json',
  'jsonb',
  'uuid',
  'enu',
  'specificType',
];
Run Code Online (Sandbox Code Playgroud)

这个数组中的每个值都变成了模式表构建器中的一个方法。