【问题标题】:How to use Scope/Relation in loopback4如何在 loopback4 中使用范围/关系
【发布时间】:2020-05-06 21:57:51
【问题描述】:

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

评论后模型

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;

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

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

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

【问题讨论】:

    标签: node.js loopbackjs loopback loopback4


    【解决方案1】:

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

    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-07-26
      • 2019-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多