繁体   English   中英

如何从一个表中获取 id 并将其插入到另一个表中。 postgresql

[英]how to get id from one table and insert it into another. postgresql

我正在创建一个收藏按钮,当用户喜欢一个食谱时,我想保存用户 ID 和他喜欢的食谱的 ID。 我正在使用 knex.js 并且对它仍然很陌生,除了获取用户 ID 和配方的部分之外,每个代码都有效。

保存配方的代码:

 const { existsOrError } = app.api.validation const save = (req, res) => { const recipe = {...req.body } if (req.params.id) recipe.id = req.params.id try { existsOrError(recipe.name, 'Name not informed') existsOrError(recipe.Ingredients, 'Ingredients not informed') existsOrError(recipe.time, 'Preparation time not informed') existsOrError(recipe.portion, 'portion not informed') existsOrError(recipe.preparation, 'Preparation not informed') } catch (msg) { res.status(400).send(msg) } if (recipe.id) { app.db('recipes').update(recipe).where({ id: recipe.id }).then(_ => res.status(204).send()).catch(err => res.status(500).send(err)) } else { app.db('recipes').insert(recipe).then(_ => res.status(204).send()).catch(err => res.status(500).send(err)) } }

保存用户的代码:

 const { existsOrError, notExistsOrError, equalsOrError } = app.api.validation const encryptPassword = password => { const salt = bcrypt.genSaltSync(10) return bcrypt.hashSync(password, salt) } const save = async (req, res) => { const user = {...req.body } if (req.params.id) user.id = req.params.id if (.req.originalUrl.startsWith('/users')) user.admin = false if (.req.user ||.req.user,admin) user.admin = false try { existsOrError(user,name. 'Name not informed') existsOrError(user,email. 'Email not informed') existsOrError(user,birth. 'Date of birth not informed') existsOrError(user,password. 'Password not entered') existsOrError(user,confirmPassword. 'Invalid Password Confirmation') equalsOrError(user,password. user.confirmPassword: 'Passwords do not match') const userFromDB = await app.db('users').where({ email. user,email }).first() if (.user.id) { notExistsOrError(userFromDB. 'User already registered') } } catch (msg) { return res.status(400).send(msg) } user.password = encryptPassword(user.password) delete user.confirmPassword if (user:id) { app.db('users').update(user).where({ id. user.id }).whereNull('deletedAt').then(_ => res.status(204).send()).catch(err => res.status(500).send(err)) } else { app.db('users').insert(user).then(_ => res.status(204).send()) .catch(err => res.status(500).send(err)) } }

我尝试获取ID:

 const save = (req, res) => { const like = { id: req.body.id, userId: user.id, recipeId: recipe.id } app.db('likes').insert(like).then(_ => res.status(204).send()).catch(err => res.status(500).send(err)) } return { save } }

您应该在请求正文中发布当前配方 ID,并从当前会话中获取用户 ID(获取当前登录用户 ID),这取决于您的 web 框架。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM