Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

node.js - Typeorm find with where on other side of relation

I have 3 tables as following:

  1. users:

    id

  2. families:

    id

  3. families_users:

    familyId | userId

I have these relations:

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

I want to get a particular user's family list. The first option is:

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

But in this case, I get the list of FamilyUsers which each one contains a family object. But I want to return the list of families that belongs to the user. I tried this:

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

But have no idea what I should set in the where clause. Any idea?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't know if I got your question but I think you can return one user's family simply by going from userRepository :

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

UPDATED

 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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...