sqlite 如何制作嵌套注解系统express.js

xcitsw88  于 11个月前  发布在  SQLite
关注(0)|答案(1)|浏览(115)

我正在尝试实现多级注解输出。也就是说,有一个注解,它可以有答案,答案也可以有答案,等等。现在我使用SQLite。以下是我到目前为止尝试的内容:模型

const Comments = sequelize.define('Comment', {
  text: {
    type: DataTypes.STRING,
    allowNull: false,
  },
})

Comments.hasMany(Comments, { as: 'Replies', foreignKey: 'parentId' })

字符串
服务

async getCommentByID(id) {
    try {
      return await comments.findByPk(id, {
        include: [
          {
            model: comments,
            as: 'replies',
            include: {
              model: comments,
              as: 'replies',
              include: {
                model: comments,
                as: 'replies',
              },
            },
          },
        ],
      })
    } catch (e) {
      throw createHttpError(500, e)
    }
  }


我想得到一个包含所有嵌套注解和嵌套注解的通用注解,等等,但这样我只能达到嵌套的第二层,但我想以某种方式自动化这一点。

2ledvvac

2ledvvac1#

正如在评论中提到的,这是一个众所周知的问题,有很多方法可以解决它。但是,既然你使用Sequelize,一个好的选择是使用一个插件来处理围绕commnets层次结构的复杂查询。
一个不错的选择是 sequelize-hierarchyNpmGitHub),它甚至列在Sequelize official docs中。
根据您的用例,可以将您的注解模型定义为:

const Comments = sequelize.define('Comment', {
  name: Sequelize.STRING,
  parentId: {
    type: Sequelize.INTEGER,
    hierarchy: true
  }
});

字符串
您可以使用以下命令检索整个注解树:

const commentsTree = await Comments.findAll({ hierarchy: true });

相关问题