【问题标题】:Typeorm find with where on other side of relationTypeorm在关系的另一边找到位置
【发布时间】:2021-01-08 00:15:43
【问题描述】:

我有 3 个表如下:

  1. 用户:

    id

  2. 家庭:

    id

  3. 家庭用户:

    familyId | userId

我有这些关系:

// User
@OneToMany(() => FamilyUser, (familyUser) => familyUser.user)
familyUsers: FamilyUser[];

// Family
@OneToMany(() => FamilyUser, (familyUser) => familyUser.family)
familyUsers: FamilyUser[];

// FamilyUser
@ManyToOne(() => User, (user) => user.familyUsers, { nullable: false })
user: User;

@ManyToOne(() => Family, (family) => family.familyUsers, { nullable: false })
family: Family;

我想获取特定用户的家庭列表。第一个选项是:

await this.familiesUsersRepository.find({
  relations: ['family'],
  where: {
    user: { id: 6 },
  },
});

但在这种情况下,我得到FamilyUsers 的列表,其中每个包含一个家庭对象。但我想返回属于用户的家庭列表。我试过这个:

return await this.familiesRepository.find({
  relations: ['familyUsers', 'familyUsers.user'],
  where: {
    // ???
  },
});

但是不知道我应该在 where 子句中设置什么。有什么想法吗?

【问题讨论】:

    标签: node.js typeorm


    【解决方案1】:

    我不知道我是否收到了您的问题,但我认为您可以通过 userRepository 简单地返回一个用户的家人:

    let idUser = 6 ;
    return await this.userRepository.findOne(idUser,{relations: ['familyUsers']});
    

    更新

     return await  this.familyRepository.createQueryBuilder('family')
       .leftJoinAndSelect('family.familyUsers', 'familyusers') 
       .where("familyusers.user = :idUser", { idUser }) // if familyusers.user doesn't work replace 'user' with the name of colmun in the table 
       .getMany()
    

    【讨论】:

    • 感谢您的回答。但它不仅不返回family作为主要对象(主要对象是用户资源),而且根本不返回family。
    • 我从你的评论中得到的是你想返回一个家庭成员列表作为主要对象吗?
    • 谢谢。虽然这有语法错误,但我明白你的意思。谢谢
    • 您可以使用其他用户的确切语法更新我的答案,祝您好运
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2019-06-14
    • 2016-08-05
    • 2023-03-17
    • 2021-07-06
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多