3

我正在尝试构建一个涉及帖子和帖子标签的应用程序。对于这些,我有一个post,tagspost_tag表。tags有我之前定义的标签,并且在应用程序的某处被建议给前端的用户。post_tag表在每一行上将帖子标签 ID作为对保存。

我使用 express.js 和 postgreql 和 pg-promise。

据我所知,我需要一个事务查询来进行创建发布操作。

此外,我需要一种机制来检测用户创建帖子时标签是否不在tags表中,以便我可以即时插入它,并且我有一个用于在表中使用的tag_id每个标签。否则,我将有一个,因为我需要分别表列和引用和表列。insertionpost_idtag_idpost_tagforeign key errorpost_tagpost_idtag_idpoststagsid

这是我迄今为止使用的 url 函数,但未成功:

privateAPIRoutes.post('/ask', function (req, res) {
    console.log('/ask req.body: ', req.body);
    // write to posts
    var post_id = ''
    var post_url = ''
    db.query(
        `
            INSERT INTO
                posts (title, text, post_url, author_id, post_type)
            VALUES
                ($(title), $(text), $(post_url), $(author_id), $(post_type))
            RETURNING id
        `,
        {
            title: req.body.title,
            text: req.body.text,
            post_url: slug(req.body.title),
            author_id: req.user.id,
            post_type: 'question'
        } // remember req.user contains decoded jwt saved by mw above.
    )
        .then(post => {
            console.log('/ask post: ', post);
            post_id = post.id
            post_url = post.post_url


            // if tag deos not exist create it here
            var tags = req.body.tags;
            console.log('2nd block tags1', tags);
            for (var i = 0; i < tags.length; i++) {
                if (tags[i].id == undefined) {
                    console.log('req.body.tags[i].id == undefined', tags[i].id);                        
                    var q1 = db.query("insert into tags (tag) values ($(tag)) returning id", {tag: tags[i].label})
                                .then(data => {
                                    console.log('2nd block tags2', tags);
                                    tags[i].id = data[0].id 


                                    // write to the post_tag
                                    db.tx(t => {
                                        var queries = [];
                                        for (var j = 0; j < tags.length; j++) {

                                            var query = t.query(
                                                `
                                                    INSERT INTO
                                                        post_tag (post_id, tag_id)
                                                    VALUES
                                                        ($(post_id), $(tag_id))
                                                `,
                                                {
                                                    post_id: post_id,
                                                    tag_id: tags[j].id
                                                }
                                            )
                                            queries.push(query);
                                        }   
                                        return t.batch(queries)
                                    })
                                        .then(data => {
                                            res.json({post_id: post_id, post_url: post_url})
                                        })
                                        .catch(error => {
                                            console.error(error);
                                        })
                                })
                                .catch(error => {
                                    console.error(error);
                                });
                }
            }
        })
        .catch(error => {
            console.error(error);
        })
});
4

1 回答 1

5

您遇到的主要问题 - 您不能db在任务或事务中使用根级对象。在事务内部尝试创建新连接会破坏事务逻辑。您需要t.tx在这种情况下使用。但是,在您的情况下,我认为您根本不需要它。

更正的代码:

privateAPIRoutes.post('/ask', (req, res) => {
    console.log('/ask req.body: ', req.body);
    db.tx(t => {
        return t.one(
            `
        INSERT INTO
        posts (title, text, post_url, author_id, post_type)
        VALUES
        ($(title), $(text), $(post_url), $(author_id), $(post_type))
        RETURNING *
        `,
            {
                title: req.body.title,
                text: req.body.text,
                post_url: slug(req.body.title),
                author_id: req.user.id,
                post_type: 'question'
            } // remember req.user contains decoded jwt saved by mw above.
        )
            .then(post => {
                console.log('/ask second query: post[0]: ', post);
                console.log('/ask second query: tags: ', req.body.tags);
                console.log('/ask second query: tags[0]: ', req.body.tags[0]);

                // the key piece to the answer:
                var tagIds = req.body.tags.map(tag => {
                    return tag.id || t.one("insert into tags(tag) values($1) returning id", tag.label, a=>a.id);
                });

                return t.batch(tagIds)
                    .then(ids => {
                        var queries = ids.map(id => {
                            return t.one(
                                `
                                INSERT INTO post_tag (post_id, tag_id)
                                VALUES ($(post_id), $(tag_id))
                                RETURNING post_id, tag_id
                                `,
                                {
                                    post_id: post.id,
                                    tag_id: id
                                }
                            )
                        });
                        return t.batch(queries);
                    });
            });
    })
        .then(data => {
            // data = result from the last query;
            console.log('/api/ask', data);
            res.json(data);

        })
        .catch(error => {
            // error
        });
});

这里的关键是简单地遍历标签 id-s,对于未设置的标签 - 使用插入。然后通过将数组传递给t.batch.


其他建议:

  • one在执行返回新记录列的插入时,您应该使用方法。
  • 您应该只在交易中使用try/catch一次。这与如何使用 Promise 有关,而不仅仅是这个库
  • 您可以将查询放入外部 SQL 文件,请参阅查询文件

要更好地理解条件插入,请参阅SELECT->INSERT

于 2016-08-21T09:57:50.230 回答