【发布时间】:2018-01-05 09:33:57
【问题描述】:
我在用于 ORM 的 Node.js 后端中使用 PostgreSQL 和 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
);
如果我想通过 objection.js 创建新的工资记录:
Salary.query()
.insert({ employee_id: 1, amount: 10 })
.then((data) => {
console.log(data);
})
.catch((err) => {
throw err;
});
我得到错误:
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)
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;
testEmployee.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;
【问题讨论】:
-
根据反对文档,您应该使用 knex 迁移创建表。
-
@SamH。你能提供一个链接吗?如果我检查docs,就会说:下一步是创建一些迁移和模型并开始使用objection.js。最好的入门方法是查看示例项目。 express 示例项目是一个简单的 express 服务器。 example-requests.sh 文件包含一堆 curl 命令,供您开始使用 REST API。
-
vincit.github.io/objection.js/#installation 在入门部分的代码示例中。它在评论中
-
@SamH。谢谢你。如果您将其写为答案,我可以关闭我的问题并奖励您的答案。
-
谢谢!让我知道提供的答案是否涵盖它
标签: node.js postgresql orm node-postgres objection.js