如何在 TypeORM postgres 中使用 leftJoinAndSelect 查询?

3 postgresql typescript typeorm node.js-typeorm

我一直在使用 TypeORM 并制作了一些实体,如下所示:

由于我不想在User和实体之间建立关系,所以我只是创建了一个名为atPost的列。userIdPost

这是问题所在。

我想连接两个表并获取数据。但我该如何使用innerJoinAndSelectorleftJoinAndSelect呢?

这是我的代码:

// getPost.ts

// Attempt 1
const first = await createQueryBuilder()
  .select('user')
  .from(User, 'user')
  .leftJoinAndSelect(Post, 'post', 'post.userId = user.id')
  .getMany() // only fetched User data without Post data

// Attempt 2
const second = await createQueryBuilder('user')
  .innerJoinAndSelect('user.id', 'userId')
  .innerJoinAndMap('user.id', Post, 'post', 'userId = post.userId')
  .getMany() // Bad request error
Run Code Online (Sandbox Code Playgroud)

但这些都不起作用......

我想加入UserPost获取所有数据(但不使用关系)。我怎样才能得到这些数据?

dyk*_*ang 8

leftJoinAndMapOne应该管用。但是你\xe2\x80\x99ve刚刚省略了第一个参数mapToProperty

\n

只要修复你的getPost.ts为这样

\n
const first = await createQueryBuilder()\n  .select(\xe2\x80\x98user\xe2\x80\x99)\n  .from(User, \xe2\x80\x98user\xe2\x80\x99)\n  // ------------------------ fixed ------------------------\n  .leftJoinAndMapOne(\xe2\x80\x98user.id\xe2\x80\x99, Post, \xe2\x80\x98post\xe2\x80\x99, \xe2\x80\x98post.userId = user.id\xe2\x80\x99)\n  // -------------------------------------------------------\n  .getMany()\n
Run Code Online (Sandbox Code Playgroud)\n