如何使用Knex创建一个TINYINT列?

5
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
    })
}

有没有不需要使用原始SQL查询的方法来完成这个操作?
3个回答

13

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

table.tinyint('rating');
我深入研究了Knex 0.21.6的代码,并发现了一些在他们的网站上甚至没有记录的可用方法列表。在TableBuilder文件knex/lib/schema/tablebuilder.js中,有一个注入到伪类模式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;
  };
});

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',
];

在这个数组中的每个值都被转化为模式表构建器中的一个方法。


1
我简直不敢相信这个没有在文档中,感谢你找到并放在这里! - darksinge
是的,在文档中简单列出它们会很容易。我也需要这个,所以我有一些空闲时间来深入研究它。不用谢。 - KeitelDOG
table.tinyint()在TypeScript(未经类型化)中无法使用。也许它没有被记录下来是因为它是内部的和实现特定的? - glen
@ElanRuusamäe,好的!我没有看列构建器方法和在阅读源代码时考虑TypeScript,这可能是不完整的代码。但我认为它不是内部的,因为我并没有真正看到一个自动化的方法使用它。其他答案中唯一的方法是table.specificType('rating', 'tinyint(1)'),而且它不是自动化的。如果我正在构建API生成器,我不能仅在使用specificType方法的自动化过程中使用字段类型tinyint,需要处理太多情况。 - KeitelDOG

4
你可以按照以下方式使用specificType
table.specificType('rating', 'tinyint(1)')

3
如果有人需要将 tinyint 用作布尔值(TINYINT(1)),可以使用table.boolean() 方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接