Prisma:未知参数别名。可用选项以绿色列出。如何解决这个问题?

Prisma: Unknown argument aliases. Available options are listed in green. How to resolve this issue?

提问人:ParzivalComputer 提问时间:8/10/2023 更新时间:8/11/2023 访问量:3514

问:

我在使用 Prisma 时遇到了一个问题,我收到错误消息“未知参数别名。可用选项以绿色列出。当我尝试将数据插入到具有名为别名的关系字段的 Prisma 模型中时,会发生此错误。我已经检查了 Prisma 文档并查看了我的代码,但我似乎找不到问题的根源。

我尝试将数据插入到我的 Prisma 模型中,该模型包含一个名为“aliases”的关系。我希望数据能够成功插入数据库。但是,我收到一条错误消息,指出“未知参数别名。可用选项以绿色列出。我对这个错误的原因感到困惑,并想了解为什么会发生这种情况以及如何解决它。 以下来源:

schema.prisma

model Language {
  id        Int      @id @default(autoincrement())
  name      String   @unique
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  pastes Paste[] @relation("paste_language")
  aliases LanguageAlias[] @relation("language_alias")
  extensions LanguageExtension[] @relation("language_extension")

  @@map("language")
}

seedLanguage.js

const { languages } = require("@codemirror/language-data");

async function createFakeLanguages(nbLanguages) {
  if (!nbLanguages || typeof nbLanguages !== "number" || nbLanguages < 0) {
    throw new Error('Le paramètre "nbLanguages" doit être un nombre positif.');
  }
  const languageList = [];
  for (let i = 0; i < languages.length && i < nbLanguages; i++) {
    const languageName = languages[i]?.name || "";
    const arrAliases = (languages[i]?.alias || [])
            .filter((alias) => typeof alias === "string")
      .map((alias) => ({ name: alias }));
    const arrExtensions = (languages[i]?.extensions || [])
      .filter((extension) => typeof extension === "string")
      .map((extension) => ({ name: extension }));
    languageList.push({
      name: languageName,      
      aliases: {
        create: arrAliases,
      },
      extensions: {
        create: arrExtensions,
      },
    });
  }

  return languageList;
}

async function seedLanguage(prisma, nbLanguages) {
  try {
    const languageList = await createFakeLanguages(
      nbLanguages
    );
    await prisma.language.createMany({
      data: languageList,
    });
  } catch (e) {
    e.functionName = "seedLanguage";
    throw e;
  }
}

module.exports = seedLanguage;

seed.js(主脚本)


const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
const seedLanguage = require("./seedLanguage");

async function runSeeds() {
  try {
    console.log("Starting seed process...");
    if (!prisma.$connect) {
      throw new Error("Prisma client has not been properly initialized.");
    }
    console.log("Executing seedLanguage()...");
    const nbLanguages = 10;
    await seedLanguage(prisma, nbLanguages);
  } catch (e) {
    console.error(
      "Error while executing seed function:",
      e.functionName
    );
    console.error("Error details:", e);
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

runSeeds();
JavaScript ORM Prisma 迁移 种子

评论

0赞 Community 8/11/2023
请编辑问题,将其限制为具有足够详细信息的特定问题,以确定适当的答案。

答:

0赞 ParzivalComputer 8/11/2023 #1

Prisma 的文档说:您不能直接使用带有嵌套关系的 createMany 函数。相反,您应该在循环中使用 create 函数来实现此目的。 下面举个例子:

// schema.prisma
model Language {
  id        Int      @id @default(autoincrement())
  name      String   @unique
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  pastes Paste[] @relation("paste_language")
  aliases LanguageAlias[] @relation("language_alias")
  extensions LanguageExtension[] @relation("language_extension")

  @@map("language")
}

model LanguageAlias {
  id         Int       @id @default(autoincrement())
  alias      String
  languageId Int
  language   Language  @relation("language_alias", fields: [languageId], references: [id])
  @@map("language_alias")
}

model LanguageExtension {
  id         Int       @id @default(autoincrement())
  extension  String
  languageId Int
  language   Language  @relation("language_extension", fields: [languageId], references: [id])
  @@map("language_extension")
}
// seedLanguage.js

/**
 * This script directly inserts foreign key data such as "alias" and "extension" into the main table as objects instead of doing so in the alias and extension tables by specifying the languageId.
 * I chose this approach because I find it simpler than linking the data with foreign keys.
 * To achieve this, I use the "create" function where the data is passed since "createMany" does not exist for relationships.
 */

const { languages } = require("@codemirror/language-data");

const defaultLanguages = [
  {
    name: "JavaScript",
    aliases: [{ alias: "JS" }, { alias: "ECMAScript" }],
    extensions: [{ extension: ".js" }, { extension: ".mjs" }],
  },
  {
    name: "Python",
    aliases: [{ alias: "Py" }],
    extensions: [{ extension: ".py" }],
  },
  {
    name: "Java",
    aliases: [{ alias: "JDK" }],
    extensions: [{ extension: ".java" }],
  },
  {
    name: "C++",
    aliases: [{ alias: "CPP" }],
    extensions: [{ extension: ".cpp" }],
  },
  {
    name: "Ruby",
    aliases: [{ alias: "RubyLang" }],
    extensions: [{ extension: ".rb" }],
  },
];

async function createFakeLanguages(nbLanguages) {
  if (!nbLanguages || typeof nbLanguages !== "number" || nbLanguages < 0) {
    throw new Error('The "nbLanguages" parameter must be a positive number.');
  }

  const languageList = [];
  for (let i = 0; i < languages.length && i < nbLanguages; i++) {
    const languageName = languages[i]?.name || "";
    const arrAliases = (languages[i]?.alias || [])
      .filter((alias) => typeof alias === "string")
      .map((alias) => ({ alias: alias }));
    const arrExtensions = (languages[i]?.extensions || [])
      .filter((extension) => typeof extension === "string")
      .map((extension) => ({ extension: extension }));

    languageList.push({
      name: languageName, // generateUniqueName(faker, nameSet),
      aliases: arrAliases, // tableau d'alias
      extensions: arrExtensions, // tableau d'ext
    });

  }
  return languageList;
}

async function seedLanguage(prisma, nbLanguages) {
  try {
    const languageList = await createFakeLanguages(nbLanguages);
    for (const languageData of languageList) {
      // or with predefined data from defaultLanguages : for (const languageData of defaultLanguages)
      const { aliases, extensions, ...language } = languageData;
      const createdLanguage = await prisma.language.create({
        data: {
          ...language,
          aliases: {
            create: aliases,
          },
          extensions: {
            create: extensions,
          },
        },
      });
      console.log(`Created language : ${createdLanguage.name}`);
    }
  } catch (e) {
    e.functionName = "seedLanguage";
    throw e;
  }
}

module.exports = seedLanguage;