0

I am working on a social app where I am having a PostComments model whos relation established with User model (comment_by).

PostComments Model

import { Entity, model, property, belongsTo} from '@loopback/repository';
import {Users} from './users.model';

@model({settings: {strict: false, strictObjectIDCoercion: true, }})
export class PostComments extends Entity {
  @property({
    type: 'string',
    id: true,
    generated: true,
  })
  comment_id?: string;

  @property({
    type: 'string',
    required: true,
  })
  post_id: string;

  @property({
    type: 'string',
    required: true,
  })
  comment_text: string;

  @property({
    type: 'date',
    default: new Date(),
  })
  created_at?: string;

  @belongsTo(() => Users)
  comment_by: string;

  [prop: string]: any;

  constructor(data?: Partial<PostComments>) {
    super(data);
  }
}

export interface PostCommentsRelations {
  // describe navigational properties here
}

export type PostCommentsWithRelations = PostComments & PostCommentsRelations;

I need to get the list of all comments with their user's name(comment by) in a single query and tried below query which returns all fields of Users model, while I need only name from users

this.postCommentsRepository.find({
  fields: {
    comment_id: true,
    post_id: true,
    comment_text: true,
    created_at: true,
    comment_by: true
  },
  include: [{ 
    relation: 'users',

  }],
  where: {
    post_id: post_id
  }
});

I also want to use loopback 3 features but couldn't find anything relative in loopback 4 doc

1 Answers1

0

You'll need to write the query as follows:

this.postCommentsRepository.find({
  fields: {
    comment_id: true,
    post_id: true,
    comment_text: true,
    created_at: true,
    comment_by: true
  },
  where: {
    post_id: post_id
  }
  include: [{ 
    relation: 'users',
    scope: {
      fields: {name: true},
    }
  }],
});

Further reading:

Rifa Achrinza
  • 1,555
  • 9
  • 19