提问者:小点点

如何使用knex和Express.js将JSON数据插入到3个表中并通过JSON响应2个表的数据


使用knex和Express.js将JSON数据插入到3个表中,并通过JSON响应2个表的数据

我们希望将数据插入到login、user和profile表中,然后通过JSON响应user和profile表数据。

db.transaction(trx => {
      trx.insert({
          password: password,
          email: user.email,
          username: user.username
        })
        .into('login')
        .returning('username')
        .then(loginusername => {
             return trx('users')
                .returning('*')
                 .insert({
                  email: user.email,
                  username: loginusername,
                  name: user.name,
                  joined: new Date()
                  })
            .returning(user[0])
            .then(user => {
             return trx('profile')
                .returning('*')
                 .insert({
                  name: name,
                  image: image,
                  username: user.username
                  })
            .then(user => {
                 res.json(user[0], profile[0]);
                  })

          })

共1个答案

匿名用户

您的思路是对的,只是我纠正了一些语法问题。为了清楚起见,我还将表记录结构移出了插入处理。

值得注意的是,.returning()不能与SQLite或MySQL一起工作。(请参阅此处的文档)。如果您正在使用这两种方法中的任何一种,那么请保存并返回输入中的数据。

// separated record data for clearer code below
let loginData = { password: password,
                email: user.email,
                username: user.username };
let userData = { email: user.email,
                username: user.username,
                name: user.name,
                joined: new Date() };
let profileData = { name: user.name,
                image: image,
                username: user.username };

let retUserName = null; // need to track the .returning() data after the .then is complete
let retUserData = null;
let retProfileData = null;

db.transaction(trx => {
    return trx.insert(loginData).into('login').returning('username')
        .then(retData => {
            retUserName = retData[0];  // save the data outside of .then
            return trx.insert(userData).into('users').returning('*')
        })
        .then(retData => {
            retUserData = retData[0];          // save the data outside of .then
            return trx.insert(profileData).into('profile').returning('*')
        })
        .then(retData => {
            retProfileData = retData[0];
            console.log({ 'userData': retUserData, 'profileData': retProfileData });
            // console.log to be replaced by your response:
            // res.json({ 'userData': retUserData, 'profileData': retProfileData });
        })
});