Knex js, sqlite database won't update unless submitted twice

Viewed 26

I have a table called "accounts" and I want to update column called "balance" when the column "total" is edited. When I submit the data it only updates the "total" column. But if I submit it again (twice) then column "balance" is updated.

Here is the code:

```function updateOne(id, job) {
  return db
    .transaction(function (t) {
      return db("jobs")
        .where({ id })
        .transacting(t)
        .select()
        .update({
          job_title: job.job_title,
          job_description: job.job_description,
          in_progress: job.in_progress,
          due_date: job.due_date,
          customer_id: job.customer_id,
          assigned_to: job.assigned_to,
          admin_id: job.admin_id,
          updated_at: timestamp,
        })
        .then(() => {
          return db("payments")
            .transacting(t)
            .sum("amount_paid as sum")
            .where("account_id", id);
        })
        .then((amountPaid) => {
          let { sum } = amountPaid[0];
          return db("accounts")
            .transacting(t)
            .where({ id })
            .update({
              total: job.total,
              balance: db.raw(`total - ${sum}`),
            });
        })
        .then(t.commit)
        .catch(t.rollback);
    })
    .then(() => {
      console.log("transaction succeeded ", id);
      return findById(id);
    })
    .catch((err) => {
      console.log("transaction failed", err);
    });```
0 Answers
Related