在knexjs中使用交易

时间:2018-08-01 14:31:53

标签: postgresql

我正在使用knexjs,我想从一个表中获取数据并使其分支到另一个表中(idk如何很好地解释它),例如我有这些数据库

表用户

id | name | email      | stories |
1  | lala | lala@gmail |    1    |

餐桌故事

id | entries | title | description |
1  |    1    |  haha |    foo      |

因此故事和条目是匹配的,每次添加新故事时,它都与条目相同,例如:

用户

id | name | email      | stories |
1  | lala | lala@gmail |    2    |

故事

id | entries | title | description |
1  |    1    |  haha |    foo      |
2  |    2    |  booo |    hoo      |

我试图做到这些

app.post('/new-story', (req, res) => {
    const { title, category, description, mature, id} = req.body;
    const stories = db.select('stories').from('users');
    db.transaction( trx => {
        trx.insert({
            stories: stories
        })
        .into('users')
        .returning('stories')
        .then( entriesBook => {

            return trx('story')
                .returning('*')
                .insert({
                    entries: entriesBook[0],
                    title: title,
                    category: category,
                    description: description,
                    mature: mature
                })
                .then( story => {
                    res.json(story[0]);
                })
        })
        .then( trx.commit)
        .catch( trx.rollback)
    })
    .catch( err => res.status(400).json('unable to create story'))
})

有人知道更好的方法吗?

0 个答案:

没有答案
相关问题