Mat*_*att 1 postgresql orm node.js node-postgres objection.js
我在 Node.js 后端使用PostgreSQL和objection.js for ORM。我只有两个具有一对一关系的简单表。我无法在表中插入新记录。
我有一个带有员工和工资表的简单数据库模式:
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
);
Run Code Online (Sandbox Code Playgroud)
如果我想通过 objection.js 创建新的工资记录:
Salary.query()
.insert({ employee_id: 1, amount: 10 })
.then((data) => {
console.log(data);
})
.catch((err) => {
throw err;
});
Run Code Online (Sandbox Code Playgroud)
我得到错误:
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)
Run Code Online (Sandbox Code Playgroud)
testSalary.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;
Run Code Online (Sandbox Code Playgroud)
测试员工.js
const { Model, snakeCaseMappers } = require('objection');
class Employee extends Model {
static get tableName() {
return 'employee';
}
static get columnNameMappers() {
return snakeCaseMappers();
}
static get jsonSchema() {
return {
type: 'object',
properties: {
employee_id: { type: 'integer' },
employee_name: { type: 'string' },
},
};
}
static get relationMappings() {
return {
salary: {
relation: Model.HasManyRelation,
modelClass: `${__dirname}/testSalary`,
join: {
from: 'employee.employee_id',
to: 'salary.employee_id',
},
},
};
}
}
module.exports = Employee;
Run Code Online (Sandbox Code Playgroud)
小智 7
需要通过idColumn在您的Model类上定义来告诉反对意见 id 列是什么。
class Salary extends Model {
static get tableName() {
return 'salary';
}
static get idColumn() {
return 'salary_id';
}
// etc
}
Run Code Online (Sandbox Code Playgroud)
使用迁移来创建表将通过创建带有命名的 id 列的表来完成这项工作id,但是如果您定义了idColumn.
| 归档时间: |
|
| 查看次数: |
2087 次 |
| 最近记录: |