【发布时间】:2020-11-18 01:09:44
【问题描述】:
我有两个具有一对多关系的相关表:
envelopes:
CREATE TABLE envelopes (
id integer DEFAULT nextval('envelope_id_seq'::regclass) PRIMARY KEY,
title text NOT NULL,
budget integer NOT NULL
);
transaction:
CREATE TABLE transactions (
id integer DEFAULT nextval('transaction_id_seq'::regclass) PRIMARY KEY,
envelope_id integer REFERENCES envelopes(id),
date date NOT NULL,
title text NOT NULL,
amount integer NOT NULL
);
每笔交易都将附加到一个信封上,同时从信封预算中删除/添加数量。
我正在尝试找出在 Express.js 中编写此查询的最佳方法,但在想出它时遇到了麻烦。
我在/envelopes/:id/transactions 的 POST 中考虑到以下几点:
...
const sql = "INSERT INTO transactions(title, amount, date, envelope_id)VALUES($1, $2, $3, $4) RETURNING *";
try {
const newTransaction = await db.query(sql, [title, amount, date, id]);
res.status(201).send(newTransaction.rows[0]);
} catch (err) {
return res.status(500).send({
error: err.message
});
}
...
不确定这是否是合适的方法。有什么建议吗?
【问题讨论】:
标签: javascript sql postgresql express