惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
博客园_首页
Google DeepMind News
Google DeepMind News
博客园 - Franky
The GitHub Blog
The GitHub Blog
GbyAI
GbyAI
有赞技术团队
有赞技术团队
Microsoft Azure Blog
Microsoft Azure Blog
G
Google Developers Blog
Recent Announcements
Recent Announcements
A
About on SuperTechFans
博客园 - 【当耐特】
博客园 - 三生石上(FineUI控件)
酷 壳 – CoolShell
酷 壳 – CoolShell
美团技术团队
罗磊的独立博客
IT之家
IT之家
博客园 - 聂微东
Stack Overflow Blog
Stack Overflow Blog
Jina AI
Jina AI
腾讯CDC
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

Mengke's blog - Mengke's coding journey

年轻不是健康的免死金牌 深圳工作机会,前端 2025 年终总结 Skill 不是 MCP 的替代品:我理解的渐进式披露与选型原则 独立开发者如何开具发票 香港银行卡开户完整指南(2025年9月最新) 招商银行储蓄卡微信动账提醒恢复方法 再谈 MCP - Model Context Protocol(MCP)详解和开发教程 Get Human-Readable "Time Ago" in TypeScript 以「asset-price-mcp」为例,从 0 开发 MCP Server Model Context Protocol (MCP) 快速开始 DeepSeek + Dify 搭建本地知识库 An elegant solution for implementing optional property types using TypeScript 2024 年终总结 Quickly Create a Fullscreen WebView with Autoplay Support for Testing 以数字开头的 ID 在 querySelector 中的处理 String casing utilities in JavaScript Check if a string is a valid color Simple Event-Emitter/PubSub pattern Find which process is running on a certain port and kill it Markdown Code block's basic and advanced syntaxes Common npm commands to use locally Pnpm aliases How to safely rename a case sensitive file/directory in a git repo? A custom hooks to use an async effect A custom hooks to use local storage state 🤩 Mengke'blog 上线的这一年 🗼 五月底去了一趟日本,记录一下我的游记和攻略 网站性能优化:如何高效预加载大型静态资源 闰年之约 - 2024年2月29日
Nest.js Typrorm 多对多关系如何创建
Mengke · 2023-04-11 · via Mengke's blog - Mengke's coding journey

Note.webp

Published on
/

3 mins read

/

––– views

Share:

使用 Typeorm 创建多对多关系的时候,可按以下方法进行。

以 Article 和 Tag 的关系为例:

@Entity()
export class Article extends CommonEntity {
  // ...
 
  // 标签
  @ManyToMany(() => Tag, (tag) => tag.articles)
  @JoinTable()
  tags: Tag[]
}
@Entity()
export class Tag extends CommonEntity {
  // 标签名
  @Column()
  @IsNotEmpty()
  label: string
 
  // 使用的文章
  @ManyToMany(() => Article, (article) => article.tags)
  articles: Article[]
}
@Module({
  imports: [TypeOrmModule.forFeature([Tag])],
  controllers: [TagController],
  providers: [TagService],
  exports: [TagService],
})
export class TagModule {}
@Module({
  imports: [TypeOrmModule.forFeature([Article]), TagModule],
  controllers: [ArticleController],
  providers: [ArticleService],
})
export class ArticleModule {}

在 article.service.ts 中调用 Tag.Service.ts 中的方法:

@Injectable()
export class ArticleService {
  list: any[]
  constructor(
    @InjectRepository(Article)
    private readonly articleRepository: Repository<Article>,
    private readonly tagService: TagService
  ) {}
 
  /**
   * 创建文章
   * @param articleCreateDto
   * @returns
   */
  async create(articleCreateDto: ArticleCreateDto) {
    // ...
 
    // 在此处就可以使用 this.tagService 来调用 Tag.service 中的方法了
    const tags = await this.tagService.findByIds(ids)
    console.log('所有 tag id:', ids, '文章中的tags', tags)
 
    // ...
  }
}

⚠️ 注意:

  • 在 article.service 中调用 tag.service 中的方法的时候要先在 article.module 中 imports 导入 TagModule 模块。

  • 还需要在 tag.module 中 exports TagService,否则报以下错。

    Nest can't resolve dependencies of the ArticleService (ArticleRepository, ?). Please make sure that the argument TagService at index [1] is available in the ArticleModule context.
     
    Potential solutions:
    - Is ArticleModule a valid NestJS module?
    - If TagService is a provider, is it part of the current ArticleModule?
    - If TagService is exported from a separate @Module, is that module imported within ArticleModule?
      @Module({
        imports: [ /* the Module containing TagService */ ]
      })

我一开始以为像普通 js 一样直接在 article.service 中导入就可以使用 tag.service 中的方法,导致一直报错,后来发现需要在 article.module 中导入 TagModule 模块才可以。

后来导入之后还是报错,就是上边这个错⬆️,最后才发现要先导出 tag.module 中先导出 TagService 才可以。

angular 的思想和普通 js 差别好大啊 😂 …