簡體   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