#TypeOrm Query

2 messages · Page 1 of 1 (latest)

tulip sinew
#

Hi guys,

I`m trying to make a query from tables with relation 1:N

The table structure:

id, name
1, example
2, example2```

```Table 2,
id, table1_id, user_id
1, 1, 30
2, 1, 40
3, 1, 50
4, 1, 60
5, 2, 32
6, 2, 42,
7,, 2, 50,
8, 2, 60```

The query is about trying to retrieve table 1 results that contains an user in table 2

My aproach is the following,

```ts
this.dataSource
      .getRepository(Table1Entity)
      .createQueryBuilder('table1')
      .leftJoinAndSelect('table1.assigned', 'table2')
      .where('table2.userId = :userId', { userId: 60 })

But this way only returns rows from Table2 that match this user:

[
  {
     id: 1,
     name: "example",
     assigned: [{id: 4, table1_id: 1, userId: 60}] // Here need to obtain all users assigned to Table1.id
  },
{
     id: 2,
     name: "example2",
     assigned: [{id: 8, table1_id: 2, userId: 60}] // Here need to obtain all users assigned to Table1.id
  },
]```

How I can query to get all users assigned that contains an especific user in Table2?

thanks in advance
quiet marshBOT
#

Please format your question or answer with Markdown formatting.
It leads to better readability and an easier time to spot problems.
For code blocks, you can wrap your block with three back ticks before and after the block, and after the first three back ticks you can add a language (like ts) to add syntax highlighting.
e.g.

```ts
@Injectable()
export class MySuperAwesomeService {
constructor(@Inject('InjectionToken') private readonly dep: SomeDependency) {}

getRandomNumber(): number {
return Math.round(Math.random() * 1000);
}
}
```

Becomes :point_down:

@Injectable()
export class MySuperAwesomeService {
  constructor(@Inject('InjectionToken') private readonly dep: SomeDependency) {}

  getRandomNumber(): number {
    return Math.round(Math.random() * 1000);
  }
}