“Column `distinctAlias.post_id` does not exist” Typeorm

“Column `distinctAlias.post_id` does not exist” Typeorm


0

I have a posts resolver which uses this logic to return posts:

const qb = Post.createQueryBuilder('post')
            .select(['post.id AS id', 'post.createdAt AS id'])
            .addSelect(
                "json_build_object('id', user.id, 'username', user.username, 'email', user.email, 'createdAt', user.createdAt, 'updatedAt', user.updatedAt)",
                'creator'
            )

        if (req.session.userId)
            qb.addSelect((qb) => {
                return qb
                    .subQuery()
                    .select('updoot.value')
                    .from(Updoot, 'updoot')
                    .where('"userId" = :userId AND "postId" = post.id', {
                        userId: req.session.userId
                    })
            }, 'voteStatus')
        else qb.addSelect('null', 'voteStatus')

        qb.innerJoin('post.creator', 'user')
            .orderBy('post.createdAt', 'DESC')
            .take(realLimitPlusOne)

        if (cursor)
            qb.where('post.createdAt < :cursor', {
                cursor: new Date(parseInt(cursor))
            })

        qb.printSql()
        const posts = await qb.getRawAndEntities()
        console.log('posts: ', posts['raw'][0])

        return {
            posts: posts['raw'].slice(0, realLimit),
            hasMore: posts['raw'].length === realLimitPlusOne
        }

I want my data to be structured in this way:

posts:  {
  id: 29,
  createdAt: 2023-02-07T06:53:39.453Z,
  creator: {
    id: 44,
    username: 'prashant',
    email: '[email protected]',
    createdAt: '2023-02-06T13:02:11.717504',
    updatedAt: '2023-02-06T13:02:11.717504'
  },
  voteStatus: -1
}

But instead of id and createdAt I get post_id and post_createdAt key names which is not compatible with my graphql types. Even though I added the aliases for these columns I am getting:

posts:  {
  post_id: 29,
  post_createdAt: 2023-02-07T06:53:39.453Z,
  creator: {
    id: 44,
    username: 'prashant',
    email: '[email protected]',
    createdAt: '2023-02-06T13:02:11.717504',
    updatedAt: '2023-02-06T13:02:11.717504'
  },
  voteStatus: -1
}

Is there any problem with my code or should I create a mapping function which key names to appropriate ones?

1 Answer
1


0

I also had a "Column ‘distinctAlias._id’ does not exist" error.
It was because I was not selecting the id in the query.
So it is not that the key names are not compatible, but that it has to allways select the id of an item and you are not selecting it.

New contributor

Machuzka is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.



Leave a Reply

Your email address will not be published. Required fields are marked *