Search code examples
node.jspostgresqlnestjstypeormnestjs-typeorm

Query limited relations using typeorm(OneToMany) relations?


I use OneToMany relations for adding messages under conversations. Here, I want to query conversation with last messages only.

Here is an example-

const conversation = await this.conversationRepository.find({
    where: [
        { user: { id: reqUser.id }, hide_from_user: false },
        { participant: { id: reqUser.id }, hide_from_participant: false }
    ],
    order: {
        updated_at: "DESC"
    },
    relations: {
        user: true,
        participant: true,
        message: true
    }
});

It returns all messages under particular conversation-

enter image description here

But I need only last message. Then how I have to query it? Please help me, here?


Solution

  • TypeOrm doesn't support that directly, to do that you have to make another query

          import { InjectRepository } from "typeorm";
    
          const conversation = await this.conversationRepository.find({
        where: [
            { user: { id: reqUser.id }, hide_from_user: false },
            { participant: { id: reqUser.id }, hide_from_participant: false }
        ],
        order: {
            updated_at: "DESC"
        },
        relations: {
            user: true,
            participant: true,
        }
    });
    
        conversation.messages = await InjectRepository(Message)
        .createQueryBuilder('message')
        .where('message.conversation = :id' , {conversation.id});
        .limit(1)  
        .orderBy('message.id', 'Desc')
        .getMany()