I've been using PostgreSQL using TypeORM and I've got some problem at getting Follower table and check if the user is in that table.
Here's my code:
// queryTest.ts
data = await getRepository(User)
.createQueryBuilder('user')
.leftJoinAndMapMany('user.id', Post, 'post', 'post.userId = user.id')
.leftJoinAndMapMany('post.id', Follow, 'follow', 'follow.userId = user.id')
// Post author's follower
.where(new Brackets(qb => {
qb.where('post.publicScope = :follower', { follower: 'Follower' })
.andWhere('post.userId = follow.followeeId')
.andWhere(':myId = follow.userId', { myId: user.id })
}))
.getMany()
And when I try to send this query, I get { } (supposed to get some user, post, follower data)
I have User, Post, Follow entities and I'm trying to get this data:
my followee's post that he set as 'Follower' (suppose I'm following some celebrity and he posted something that is just for followers, and I'm trying to get that data)
OR I'm also thinking of makig 2 entities (Follower, Followee) that have ManyToMany relation. Could any body help me with this?
The problem is that you are mapping Post and Follow to the wrong property, the first param that you gave 'user.id' is wrong, this param must be the property that you want to save the Post or Follow in, so it should be something like this:
data = await getRepository(User)
.createQueryBuilder('user')
.leftJoinAndMapMany('user.post', Post, 'post', 'post.userId = user.id')
.leftJoinAndMapMany('post.follow', Follow, 'follow', 'follow.userId = user.id')
.where(new Brackets(qb => {
qb.where('post.publicScope = :follower', { follower: 'Follower' })
.andWhere('post.userId = follow.followeeId')
.andWhere(':myId = follow.userId', { myId: user.id })
}))
.getMany()
Note that you MUST create these properties (post, follow) in the User entity. However, if you used OneToMany or ManyToOne or OneToOne relations in there, you shouldn't use leftJoinAndMapMany, just use leftJoinAndSelect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With