立即获取 mySql 中自动生成的字段以供使用

Immediately grab auto-generated field in mySql for use

在此获取期间,它会创建一个新记录,并自动递增 mySql table 中名为“employee_id”的字段。那部分工作正常。

但是现在我想添加的是,如果可能的话,立即在同一个函数中,使用自动生成的值设置状态。这可能吗?

这是我当前状态下的函数。上面写着“this.setState({selectedEmployee...”的那一行目前打破了它。我想要做的是设置 selectedEmployee 状态,这样我就可以在 'createQuestions' 函数中使用它。

createInterview() {
    fetch(API_URL + `/interview/create`, {
      method: "PUT",
      body: JSON.stringify({
        employee: this.state.employee,
        employment_level: this.state.employment_level,
        audit_id: this.props.auditId,
      }),
      headers: { "Content-Type": "application/json" },
    })
      .then((res) => {
        if (!res.ok) {
          throw new Error();
        }
        return res.json();
      })
      .then((data) => console.log(data))
      .then((data) => this.setState({ selectedEmployeeId: data.employee_id }))
      .catch((err) => console.log(err))
      .then(() => this.createQuestions())
      .then(() => this.getAllInterviews());

    this.setState({ showHide: false });
  }

这是我的 API 电话:

app.put("/interview/create", function (req, res) {
    console.log("It is getting to the route");
    const employee = req.body.employee;
    const employment_level = req.body.employment_level;
    const audit_id = req.body.audit_id;
    console.log(`employee: ${employee}`);
    console.log(`employment_level: ${employment_level}`);
    console.log(`audit_id: ${ audit_id }`);
    connection.getConnection(function (err, connection) {
        connection.query(
        `INSERT INTO audit_interview (employee, employment_level, audit_id)
            VALUES (?, ?, ?)`,
            [
                employee,
                employment_level,
                audit_id
            ],
        function (error, results, fields) {
            if (error) throw error;
            res.json(results);
            console.log(`Interview has been created`);
        }
    );
    connection.release();
  });
});

是的,你可以获得LAST_INSERT_ID() back in your nodejs program. In your completion callback, add a reference to results.insertId的这个值,也许是这样的。它是传递给该回调的 results 项目的属性。

        function (error, results, fields) {
            if (error) throw error;
            const insertId = results.insertId;
            res.json(results);
            console.log(`Interview has been created`);
        }

而且,与这样的查询不同,

SELECT MAX(id) FROM table; /* don't do this, it's wrong! */

使用那个 results.insertId 值是 race-condition-proof 即使是大规模并发。