ORM - 拒绝错误:列“id”不存在

时间:2018-01-05 09:33:58

标签: node.js postgresql orm node-postgres objection.js

我在Node.js后端使用 PostgreSQL objection.js进行ORM。我只有两个简单的表,一对一的关系。我无法在表格中插入新记录。

我有一个包含员工和工资表的简单数据库模式:

ExcelChart ec = ws.Drawings.AddChart("LineChart01", eChartType.LineMarkers);

var rangeX = ws.Cells["A2:A11"]; // X-Axis
var range1 = ws.Cells["B2:B11"]; // 1st LineSerie

ExcelLineChartSerie serie1 = (ExcelLineChartSerie)ec.Series.Add(range1, rangeX);

serie1.MarkerLineColor = System.Drawing.Color.Gray;
serie1.MarkerSize = 10;
serie1.Fill.Color = System.Drawing.Color.Gray;
serie1.LineColor = System.Drawing.Color.Gray;
serie1.Border.LineStyle = eLineStyle.Solid;

如果我想通过objection.js创建新的工资记录:

CREATE TABLE employee (
    employee_id SERIAL PRIMARY KEY,
    employee_name VARCHAR
);

INSERT INTO employee (employee_name) VALUES ('james');

CREATE TABLE salary (
  salary_id SERIAL PRIMARY KEY,
  employee_id SERIAL UNIQUE,
  FOREIGN KEY (employee_id) REFERENCES employee (employee_id),
  amount integer
);

我收到错误:

Salary.query()
          .insert({ employee_id: 1, amount: 10 })
          .then((data) => {
            console.log(data);
          })
          .catch((err) => {
            throw err;
          });

testSalary.js

Unhandled rejection error: column "id" does not exist
at Connection.parseE (./node_modules/pg/lib/connection.js:546:11)
at Connection.parseMessage (./node_modules/pg/lib/connection.js:371:19)
at TLSSocket.<anonymous> (./node_modules/pg/lib/connection.js:114:22)
at emitOne (events.js:115:13)
at TLSSocket.emit (events.js:210:7)
at addChunk (_stream_readable.js:252:12)
at readableAddChunk (_stream_readable.js:239:11)
at TLSSocket.Readable.push (_stream_readable.js:197:10)
at TLSWrap.onread (net.js:589:20)

testEmployee.js

const { Model, snakeCaseMappers } = require('objection');

class Salary extends Model {
  static get tableName() {
    return 'salary';
  }

  static get columnNameMappers() {
    return snakeCaseMappers();
  }

  static get jsonSchema() {
    return {
      type: 'object',

      properties: {
        salary_id: { type: 'integer' },
        employee_id: { type: 'integer' },
        amount: { type: 'integer' },
      },
    };
  }

  static get relationMappings() {
    return {
      employee: {
        relation: Model.BelongsToOneRelation,
        modelClass: `${__dirname}/testEmployee`,
        join: {
          from: 'salary.employee_id',
          to: 'employee.employee_id',
        },
      },
    };
  }
}

module.exports = Salary;

2 个答案:

答案 0 :(得分:1)

我的猜测是,这与对引擎盖的依赖有关。在the docs中,有一个代码段,建议通过Knex迁移创建表。也许这样做可以解决您的问题,因为Knex可能会创建一个Objection期望存在的id列。

答案 1 :(得分:0)

需要通过在idColumn类上定义Model来告知异议id列是什么。

class Salary extends Model {
  static get tableName() {
    return 'salary';
  }

  static get idColumn() {
    return 'salary_id';
  }
  // etc
}

使用迁移来创建表的方法是通过创建其id列名为id的表来完成这项工作,但是如果您定义idColumn,则可以在不进行迁移的情况下使用异议。