在 sequelize 中加入相同的 table 并在 excel 中打印

join same table in sequelize and print in excel

我想在excel

中打印parent名字

这是我的代码


function getReportT0Print(req, res) {
  return new Promise((resolve, reject) => {
    Product.findAll({
      where: {
        $and: [
          {
            public: true,
            visible: true,
            ancestry: {
              $not: null,
            },
          },
        ],
      },
      include: [
        {
          model: ormDb.Document,
          required: false,
        },
      ],
      attributes: ["name", "slug", "folder_path"],
    })
      .then(function (data) {
        // console.log("data" + data.length);
        var rows = [];
        rows.push(["Product Name", "Slug", "File Path", "Product Parent Name"]);
        data.map(function (product) {
          rows.push([
            product.name,
            product.slug,
            product.folder_path,
            (here i need to print parent name)
          ]);
        });
        var workbook = new Excel.Workbook();
        var sheet = workbook.addWorksheet("products_with_tags");
        sheet.addRows(rows);
        resolve(workbook);

        return res.send("successfull");
      })
      .catch(function (err) {
        reject(err);
      });
  });
}

我可以打印 name, slug,folder_path 但我不知道如何在 excel 文件中打印 parent name 因为 parent 名称不存在,但我用 parent_id 代替了 parent 名称并想打印 parent 名称

我的SQltable看起来像这样 ("id" "name" "version" "published" "reviewed" "visible" "public", "parent_id")

您需要像这样注册两个 Product 模型之间的关联:

Product.belongsTo(Product, { foreignKey: 'parent_id', as: 'parent' });

例如,您可以将它放在创建 Sequelize 实例的模型模块文件之外的某个模块中。

要使用此关联,您需要使用与 Document:

相同的 include 选项
Product.findAll({
      where: {
        $and: [
          {
            public: true,
            visible: true,
            ancestry: {
              $not: null,
            },
          },
        ],
      },
      include: [
        {
          model: Product,
          as: 'parent',
          required: false, // or true if parent_id is required field 
          // or you wish to get all products with parents
          attributes: ["name", "slug", "folder_path"],
        },
        {
          model: ormDb.Document,
          required: false,
        },
      ],
      attributes: ["name", "slug", "folder_path"],
    })