用外键将数据插入表中

时间:2019-10-28 16:52:59

标签: node.js react-native

我想获取的用户ID是帖子表中的外键... 并插入帖子表中!!! 如何从登录名中将user_id插入帖子????

我想从此函数获取users_id ...

app.post("/login", async (req, res, next) => {
    const { username, password } = req.body;
    if (!username || !password) {
      res.json({
        success: false,
        message: "there is noo login"
      });
    }
    const query = SQL`SELECT username ,password,users_id FROM Users WHERE username = ${username} AND password = ${password}`;
    const student = await db.all(query);
    if (student.length === 0) {
      res.json({
        success: false,
        message: "Please check you login"
      });
    } else {
      res.json({
        success: true,
        user: student,

      });
    }
  });

并通过此功能将其插入此表...

app.post("/post", async (req, res, next) => {
    const { title, text } = req.body;

    if (!title || !text ) {
      res.json({
        success: false,
        message: "Complete your Post "
      });
    }

    try  {
        const query = `INSERT INTO Post (title,text,users_id) VALUES 
        ('${title}','${text}',????????) `;
        console.log(second_query);
        const query2 = await db.run(query );
        if (query2.length === 0) {
          res.json({
            success: false,
            message: "Please check your post"
          });
        }

        res.json({
          success: true,
          dat: query2.stmt.lastID,

        });
      }
    } catch (err) {
      console.log("===err===>", err);
    }

    next();
  });

1 个答案:

答案 0 :(得分:0)

我假设您使用的是裸机nodejs,没有任何库或框架来处理当前登录的用户会话。我建议您研究教程以正确实施和处理管理用户会话。当您拥有易于使用和流行的库时,编写自己的库是一个非常糟糕的主意。使用框架,您将拥有一个表示当前登录用户的全局对象。因此,您的代码将如下所示:INSERT INTO Post (title,text,users_id) VALUES ('${title}','${text}',globalUserObject.id)