【问题标题】:Inserting record into a relational table with a foreign key?使用外键将记录插入关系表?
【发布时间】: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


    【解决方案1】:

    也许尝试创建一个事务,这样要么所有查询都被执行,要么不执行。

    BEGIN TRANSACTION
    
    INSERT INTO transactions (title, amount, date, envelope_id) VALUES ($1, $2, $3, $4);
    
    UPDATE envelopes SET
        budget = budget - <Deduction Value>
        WHERE id = <envelope ID>;
    
    COMMIT TRANSACTION;
    
    SELECT * FROM transactions ORDER BY created_at DESC LIMIT 1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多