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

huangapple go评论90阅读模式
英文:

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

问题

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

我尝试将包含名为"aliases"的关系的数据插入我的Prisma模型。我期望数据能成功插入到数据库中。然而,我收到了一个错误消息,其中说"未知参数别名。可用选项以绿色显示。" 我对这个错误的原因感到困惑,想要了解为什么会发生这种情况以及如何解决它。

以下是相关的源代码:

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('参数"nbLanguages"必须是正数。');
  }
  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("开始种子数据生成过程...");
    if (!prisma.$connect) {
      throw new Error("Prisma客户端未正确初始化。");
    }
    console.log("执行seedLanguage()...");
    const nbLanguages = 10;
    await seedLanguage(prisma, nbLanguages);
  } catch (e) {
    console.error(
      "执行种子函数时出错:",
      e.functionName
    );
    console.error("错误详情:", e);
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

runSeeds();
英文:

I'm encountering an issue with Prisma where I'm getting the error message "Unknown argument aliases. Available options are listed in green." This error occurs when I try to insert data into a Prisma model with a relation field named aliases. I've checked the Prisma documentation and reviewed my code, but I can't seem to find the source of the problem.

I attempted to insert data into my Prisma model that includes a relationship named "aliases." I expected the data to be successfully inserted into the database. However, I received an error message stating "Unknown argument aliases. Available options are listed in green." I'm puzzled about the cause of this error and would like to understand why it's happening and how to resolve it.
Below sources :

schema.prisma

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

  pastes Paste[] @relation(&quot;paste_language&quot;)
  aliases LanguageAlias[] @relation(&quot;language_alias&quot;)
  extensions LanguageExtension[] @relation(&quot;language_extension&quot;)

  @@map(&quot;language&quot;)
}

seedLanguage.js

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

async function createFakeLanguages(nbLanguages) {
  if (!nbLanguages || typeof nbLanguages !== &quot;number&quot; || nbLanguages &lt; 0) {
    throw new Error(&#39;Le param&#232;tre &quot;nbLanguages&quot; doit &#234;tre un nombre positif.&#39;);
  }
  const languageList = [];
  for (let i = 0; i &lt; languages.length &amp;&amp; i &lt; nbLanguages; i++) {
    const languageName = languages[i]?.name || &quot;&quot;;
    const arrAliases = (languages[i]?.alias || [])
			.filter((alias) =&gt; typeof alias === &quot;string&quot;)
      .map((alias) =&gt; ({ name: alias }));
    const arrExtensions = (languages[i]?.extensions || [])
      .filter((extension) =&gt; typeof extension === &quot;string&quot;)
      .map((extension) =&gt; ({ 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 = &quot;seedLanguage&quot;;
    throw e;
  }
}

module.exports = seedLanguage;

seed.js (main script)


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

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

runSeeds();

答案1

得分: 0

以下是翻译好的部分:

// 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

/**
 * 此脚本将外键数据直接插入主表中,作为对象,而不是在别名和扩展表中指定languageId来插入数据。
 * 我选择这种方法,因为我觉得它比使用外键链接数据更简单。
 * 为了实现这一目标,我在传递数据时使用了create函数,因为关系中不存在createMany函数。
 */

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, // 别名数组
      extensions: arrExtensions, // 扩展数组
    });
  }
  return languageList;
}

async function seedLanguage(prisma, nbLanguages) {
  try {
    const languageList = await createFakeLanguages(nbLanguages);
    for (const languageData of languageList) {
      // 或者使用预定义的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;
英文:

Documentation of Prisma says : you cannot use the createMany function with nested relations directly. Instead, you should use the create function in a loop to achieve this.
Below an example :

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

  pastes Paste[] @relation(&quot;paste_language&quot;)
  aliases LanguageAlias[] @relation(&quot;language_alias&quot;)
  extensions LanguageExtension[] @relation(&quot;language_extension&quot;)

  @@map(&quot;language&quot;)
}

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

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

/**
 * This script directly inserts foreign key data such as &quot;alias&quot; and &quot;extension&quot; 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 &quot;create&quot; function where the data is passed since &quot;createMany&quot; does not exist for relationships.
 */

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

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

async function createFakeLanguages(nbLanguages) {
  if (!nbLanguages || typeof nbLanguages !== &quot;number&quot; || nbLanguages &lt; 0) {
    throw new Error(&#39;The &quot;nbLanguages&quot; parameter must be a positive number.&#39;);
  }

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

    languageList.push({
      name: languageName, // generateUniqueName(faker, nameSet),
      aliases: arrAliases, // tableau d&#39;alias
      extensions: arrExtensions, // tableau d&#39;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 = &quot;seedLanguage&quot;;
    throw e;
  }
}

module.exports = seedLanguage;

huangapple
  • 本文由 发表于 2023年8月10日 21:16:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76876082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定