Sequelize - 向表中添加新行并关联表

时间:2016-02-29 20:50:42

标签: javascript mysql node.js express sequelize.js

我正在使用Sequelize ORM和MySql,目前遇到了在表和关联表中创建新条目的问题。     我的模特:      制品

serial

我想要达到的目的是在适当的文章中添加评论,同时在" commented_articles"中添加新的细胞。 "评论"表包含对文章和图片的评论(还有一个" commented_images"表)。 我试图使用addComments方法,但它不起作用。我究竟做错了什么?     感谢

1 个答案:

答案 0 :(得分:2)

我解决了我的问题。脏版是:

addNewCommentToArticle: function (req, res) {
    var id_parent = req.body.id_parent,
        user_id = req.body.user_id,
        nick = req.body.nick,
        title = req.body.title,
        comment = req.body.comment;
    models.articles.findByPrimary(req.params.id)
        .then(function (createdArticle) {
            models.comments.create({
                id_parent: id_parent,
                user_id: user_id,
                nick: nick.trim(),
                title: title.trim(),
                comment: comment.trim()
            }).then(function (newComment) {
                createdArticle.addComments(newComment)
                    .then(function () {
                        res.json(newComment);
                    })
                    .catch(function (e) {
                        res.json(e);
                    });
            })
     });
 }

希望有人发现它有用。