0

我正在开发一个社交应用程序,其中我有一个与用户模型(comment_by)建立关系的 PostComments 模型。

PostComments 模型

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;

我需要在单个查询中获取带有用户名(评论者)的所有评论列表,并在下面尝试返回用户模型的所有字段的查询,而我只需要用户名

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
  }
});

我也想使用环回 3 功能,但在环回 4 文档中找不到任何相关内容

4

1 回答 1

0

您需要按如下方式编写查询:

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},
    }
  }],
});

进一步阅读:

于 2020-05-06T13:57:51.773 回答