登录/注册

Sequelize中批量删除

用户头像管理员41阅读

Sequelize中有批量查询findAll、批量创建bulkCreate,同时可以通过where进行条件筛选进行批量更新,在一次需要进行评论删除的功能实现时,我没有在文档中找到批量删除,原本是打算使用[Op.in]然后传递数组实现,在查询相关文章后发现where中可以直接传递数组。

例:

let rows = await Comment.destroy({
    where: {
    id:[1,2,3]
   }
});
这样的话只要Model中有ID在数组中都可以被删除,下面贴一下我删除评论功能的实现代码,作为参考,因为删除评论需要递归查询相关的子评论进行删除,所以也是需要删除数组。
import { Comment } from "@/db";
import { sign } from "@/common/guards/auth";
import express, { NextFunction, Response, Request } from "express";
const router = express.Router();

interface whereType {
  id:string[];
  commentator?: string;
}

/**
 * 传递需要删除的评论的ID,递归查询并返回所有子评论
 * @params id {string} 需要删除的初始ID
 * @return comments {string[]} 所有子评论的ID
 */
async function getAllComment(id: string) {
  let comments: string[] = [id];
  /** 查询单个评论的子评论并推进数组*/
  async function getCommentId(id: string) {
    let comment_id = await Comment.findAll({
      where: {
        superior: id,
      },
      attributes: ["id"],
    });
    comments.push(...comment_id.map(item => item.id));
    if (comment_id.length) {
      for (let index = 0; index < comment_id.length; index++) {
        await getCommentId(comment_id[index].id);
      }
    }
  }
  await getCommentId(id);
  return comments;
}

router.delete("/comment/:id", sign, async (req: Request, res: Response, next: NextFunction) => {
  let id = req.params.id;
  let deleteWhere: whereType = { id: await getAllComment(id) };
  if (req.authentication != "admin") deleteWhere.commentator = req.userId + "";
  let rows = await Comment.destroy({
    where: deleteWhere as unknown as whereType,
  });

  res.json({
    success: !!rows,
    message: `删除${rows ? "成功" : "失败"}`,
  });

});
export default router;
Preview
登录后评论