javascript - TypeORM:使用自定义属性查询多对多

标签 javascript mysql typescript nestjs typeorm

各位,我是 TypeORM 的新手,我需要一些帮助。

我尝试使用这样的自定义属性创建多对多关系 docs here

And here my problems.

我想要这样的查询结果..

{
    "id": 1,
    "username": "John Doe",
    "products": [
        {
            "id": 1,
            "title": 'A shirt',
            "description": 'lorem ipsum'
        }
    ]
}

但是我得到了...

{
    "id": 1,
    "username": "John Doe",
    "products": [
        {
            "id": 1,
            "userId": 1,
            "productId":1
        }
    ]
}

这里是我查询的方式

const user = await this.userRepository.findOne({
      where: { id },
      relations: ["products"],
});

这是我的代码。

用户产品实体

// user-product.entity.ts

@Entity()
export class UserProduct extends BaseEntity {
  
  @PrimaryColumn()
  public id: number;

  @Column()
  public userId!: number;

  @Column()
  public productId!: number;

  @ManyToOne(
    () => User,
    (user) => user.products
  )
  public user!: User;

  @ManyToOne(
    () => Product,
    (product) => product.users
  )
  public product!: Product;

}

用户实体

// user.entity.ts

@Entity()
export class User extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  username: string;
   
  @OneToMany(()=> UserProduct, userToProduct => userToProduct.user)
  public products!: UserProduct[];

}

产品实体

// product.entity.ts
@Entity()
export class Product extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column({ nullable: true })
  subtitle: string;

  @Column({ nullable: true })
  description: string;


  @OneToMany(
    () => UserProduct,
    (userProduct) => userProduct.product
  )
  public users!: UserProduct[];

}

I would like to know. How to get the result like the above?

最佳答案

我想你想知道如何加载子关系

relations - relations need to be loaded with the main entity. Sub-relations can also be loaded (shorthand for join and leftJoinAndSelect)

您可以查看此文档:Find Options

你可以这样做:

const user = await this.userRepository.findOne({
      where: { id },
      relations: ["products.product"],
});

关于javascript - TypeORM:使用自定义属性查询多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62474805/

相关文章:

mysql - javax.ejb.EJBException : javax. persistence.PersistenceException : org. hibernate.exception.DataException: 无法执行语句

angular - 错误 : (SystemJS) XHR error (404 Not Found) loading ng2-appinsights

java - 从 netbeans 中的 sql 表中获取值

php - 通过 PHP INI 添加 MsSQL

node.js - Jest 通过了测试,但 --covering 选项未拾取文件

angularjs - typescript : AngularJS retrieving a result object

javascript - jquery mobile 和两个不同的 jquery 版本

javascript - Sinon - 返回不是函数

javascript - Bootstrap 4 - 水平对齐的 Accordion

javascript - 将句子转换为首字母大写/驼峰式大小写/正确大小写