数据库中的关系表"/>
使用在用户注册时创建的'id'发布到数据库中的关系表
我有两个表,如下所示
“>
第一个表供用户使用,并通过客户端的注册表进行填充。创建新用户时,我需要在第二个“配额”表中填充日期,金额并与用户ID关联。 “ user_id”用于在GET中提取配额信息并显示客户端。我在创建时使用'id'填充第二个表时遇到问题。我正在使用knex进行所有查询。我会使用join在knex中链接它们吗?
服务器
hydrateRouter // get all users .route('/api/user') .get((req, res) => { knexInstance .select('*') .from('hydrate_users') .then(results => { res.json(results) }) }) .post(jsonParser, (req, res, next) => { // register new users const { username, glasses } = req.body; const password = bcrypt.hashSync(req.body.password, 8); const newUser = { username, password, glasses }; knexInstance .insert(newUser) .into('hydrate_users') .then(user => { res.status(201).json(user); }) .catch(next); })
client
export default class Register extends React.Component { constructor(props) { super(props); this.state = { username: '', password: '', glasses: 0 } } handleSubmit(event) { event.preventDefault(); fetch('http://localhost:8000/api/user', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.state) }) .then(response => response.json()) .then(responseJSON => { this.props.history.push('/login'); }) }
用于显示水量的服务器侧路线
hydrateRouter .route('/api/user/waterconsumed/:user_id') // display water consumed/day .all(requireAuth) .get((req, res, next) => { const {user_id} = req.params; knexInstance .from('hydrate_quotas') .select('amount') .where('user_id', user_id) .first() .then(water => { res.json(water) }) .catch(next) })
谢谢!
我有两个表,如下表所示,第一个表供用户使用,并通过客户端的注册表进行填充。创建新用户时,我需要填充第二个“ quotas”表...
回答如下:获取插入行的ID
更多推荐
使用在用户注册时创建的'id'发布到数据库中的关系表
发布评论