环回4包含嵌套关系 [英] Loopback 4 include nested relations

查看:71
本文介绍了环回4包含嵌套关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近的回送团队增加了对嵌套关系的支持.参考 https://loopback.io/doc/zh/lb4/HasMany-relation.html#query-multiple-relations .但这并未涵盖其余的api网址以获取嵌套关系.这就是我尝试过的.

Recently loopback team added support to the inclusion of nested relation. Reference https://loopback.io/doc/en/lb4/HasMany-relation.html#query-multiple-relations. But it doesn't cover the rest api url to get nested relations. This is what I have tried.

我有三种型号的用户,购物车,产品.用户有多个购物车,并且购物车属于产品.我的环回/cli版本是1.27.0

I have three models users, carts, products. Users have has-many carts and carts belongs-to product. My loopback/cli version is 1.27.0

user.repository.ts

user.repository.ts

constructor(
    @inject('datasources.farm') dataSource: FarmDataSource,  @repository.getter('CartRepository') protected cartRepositoryGetter: Getter<CartRepository>,
  ) {
    super(Users, dataSource);
    this.carts = this.createHasManyRepositoryFactoryFor('carts', cartRepositoryGetter,);
    this.registerInclusionResolver('carts', this.carts.inclusionResolver);

  }

cart.repository.ts

cart.repository.ts

 constructor(
    @inject('datasources.farm') dataSource: FarmDataSource, @repository.getter('UsersRepository') protected usersRepositoryGetter: Getter<UsersRepository>, @repository.getter('ProductRepository') protected productRepositoryGetter: Getter<ProductRepository>,
  ) {
    super(Cart, dataSource);
    this.product = this.createBelongsToAccessorFor('product_id', productRepositoryGetter);
    this.registerInclusionResolver('product', this.product.inclusionResolver);

    this.users = this.createBelongsToAccessorFor('user_id', usersRepositoryGetter);
    this.registerInclusionResolver('users', this.users.inclusionResolver);
  }
}

product.repository.ts

product.repository.ts

constructor(
    @inject('datasources.farm') dataSource: FarmDataSource, @repository.getter('PurchaseRepository') protected purchaseRepositoryGetter: Getter<PurchaseRepository>, @repository.getter('StockRepository') protected stockRepositoryGetter: Getter<StockRepository>, ) {
    super(Product, dataSource);


    this.registerInclusionResolver('stocks', this.stocks.inclusionResolver);
    this.registerInclusionResolver('purchases', this.purchases.inclusionResolver);

  }

预先感谢

推荐答案

我已经成功实现了与MySQL作为数据源的关系.该文档确实共享使用非关系数据库将具有意外的行为.如果是这种情况,那么您应该检查一下它们的进度..环回关系公开问题

I have successfully implemented relations with MySQL as the datasource. The documentation does share that using a non-relational databases will have unexpected behavior. If that's your case, then you should check out their progress.. loopback relations open issue

我们的示例模型将是问题"(源)和响应"(目标).问题与响应有 hasMany 关系

Our example models will be Question (Source) and Response (Target). Question has a hasMany relation with Response

配置模型以处理关系,一次处理一个关系

  • 您应该使用@hasMany装饰器将新属性添加到Question模型中,

  • You should add a new property to your Question model with the @hasMany decorator which will look something like this

@hasMany(() => Response, {keyTo: 'question_id', name: 'responses'})响应?:Response []

@hasMany(() => Response, {keyTo: 'question_id', name: 'responses'}) responses?: Response[]

请注意keyTo是允许该关系正常工作的外键,并且name只是该关系的名称

Notice that keyTo is the foreign key that will allow the relation to work and name is just the name of the relation

如果尚未定义外键属性,请在您的Question模型中添加它.可以使用常规的@property()装饰器完成,也可以使用以下

In your Question model add the foreign key property if you haven't defined it already. It can be done with the regular @property() decorator OR like the following

@belongsTo(()=>问题,{名称:'question',keyTo:'question_id'})question_id ?:数字;

@belongsTo(() => Question, {name: 'question', keyTo: 'question_id'}) question_id?: number;

在源模型存储库(问题)中,您需要提供对目标模型(响应)的访问,类似于以下内容:

Within your source model repository (Question) you need to provide access to target model (Response) similar to the following:

export class QuestionRepository extends DefaultCrudRepository<
  Question,
  typeof Question.prototype.question_id,
  QuestionRelations
  > {
  public readonly responses: HasManyRepositoryFactory<
    Response,
    typeof Question.prototype.question_id
  >;
  constructor (
    @inject('datasources.myDB') dataSource: MyDBDataSource,
    @repository.getter('ResponseRepository') responseRepository: Getter<ResponseRepository>,
  ) {
    super(Question, dataSource);
    this.responses = this.createHasManyRepositoryFactoryFor(
      'responses',
      responseRepository
    );
    this.registerInclusionResolver('responses', this.responses.inclusionResolver);
  }
}

  • 确保您添加了注册包含解析器的最后一行
  • 现在应该建立您的关系!要使用它,您只需在控制器中创建一个远程方法.回送团队确实传达了应该为关系案例创建一个新的单独控制器的信息.因此,在这种情况下,您将创建一个名为question-response.controller.ts

    Now your relation should be set up! To use it you would just want to create a remote method within a controller. The loopback team does communicate that a new separate controller should be created for relational cases. So in this case you would create a controller called question-response.controller.ts

    现在,您只需要将过滤器对象传递给您感兴趣的方法即可.让我们使用.find()方法是最简单的方法.它应该如下所示:

    Now you will just need to pass a filter object to the method you are interested in. Lets just use the .find() method since its the easiest. It should look like the following:

    @get('/question/{questionId}/response_data')
      async findQuestionWithResponses(
        @param.path.number('questionId') questionId: typeof Question.prototype.question_id,
          @param.query.object('filter', getFilterSchemaFor(Question)) filter?: Filter<Question>
      ): Promise<any> {
        if (!filter) filter = {};
        filter.include = [{ relation: 'responses' }];
        return this.questionRepository.findById(questionId, filter);
      }
    

    希望这会有所帮助!

    对于嵌套关系,它也类似于以下文档中的示例,只需确保已设置所有关系:)

    Also for the nest relation it would look like the example in the documentation like the following, just make sure all your relations are set up :)

    customerRepo.find({
      include: [
        {
          relation: 'orders',
          scope: {
            where: {name: 'ToysRUs'},
            include: [{relation: 'manufacturers'}],
          },
        },
      ],
    });
    

    这篇关于环回4包含嵌套关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆