环回4:多对多关系

问题描述 投票:0回答:1

我试图实现一种方法来过滤具有ManytoMany关系的表中的数据。

我有以下表格job,job_category和category。

到目前为止,我正在考虑使用job_id对job_category进行查询,然后使用该结果使用IN()添加条件,但我也没有找到任何方法来实现此选项。

问题:

  1. 如何在Loopback 4中实现ManytoMany关系?
  2. 如何使用IN过滤查询?

PD我可以使用$ inq来回答问题2。

filter.where = {
   ...filter.where,
   id: {inq: [2, 7]},
};
loopback v4l2loopback
1个回答
0
投票

根据您的问题的上下文,可以在lb4中实现多对多关系,如下所示。

工作模型(样本) -

    @model({
      name: 'jobs',
    })
    export class Job extends Entity {
      @property({
        type: 'number',
        id: true,
      })
      id: number;

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

      // Other columns of the table.....

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

类别模型(样本) -

    @model({
      name: 'categories',
    })
    export class Category extends Entity {
      @property({
        type: 'number',
        id: true,
      })
      id: number;

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

      // Other columns of the table.....

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

在作业类别关系模型中,我们将实现与作业和类别模型的属于关系。这将确保m:n关系。

    @model({
      name: 'job_categories',
    })
    export class JobCategory extends Entity {
      @property({
        type: 'number',
        id: true,
      })
      id: number;

      @belongsTo(() => Job)
      job_id: number;

      @belongsTo(() => Category)
      category_id: number;

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

现在,使用lb4 CLI,您可以为作业类别模型创建存储库和REST控制器,并使用其中的查找方法来获取数据。不幸的是,lb4中尚未实现find类中的include参数。它仍然是WIP。请参阅loopback-next repo中的this线程以获取更新。在此之前,您可能必须添加自定义逻辑t控制器或存储库类来实现此目的。我的两个建议方法如下。

  1. 配置属于存储库中的关系(请参阅文档here)并在控制器内部使用它来获取响应相关数据(请参阅实现here)。您可能需要为此创建自己的响应模型。我们为此创建了自己的DTO。您也可以返回“任何”类型作为响应,但不建议这样做。
  2. 如果需要,您可以执行自己的连接查询。这是本机查询方法。但是,遗憾的是,还没有实现在存储库类中再次执行函数。见here。它有dts可用。因此,我们实施了一项工作直到实施。我们创建了一个Base存储库类,它将由我们的应用程序中的所有存储库类继承(用扩展的AppDefaultCrudRepository替换所有扩展的DefaultCrudRepository)。这是基本存储库的实现。
    export abstract class AppDefaultCrudRepository<
      T extends Entity,
      ID
    > extends DefaultCrudRepository<T, ID> {
      constructor(
        entityClass: typeof Entity & {
          prototype: T;
        },
        dataSource: AppDataSource,
      ) {
        super(entityClass, dataSource);
      }

      execute(
        command: Command,
        parameters: NamedParameters | PositionalParameters,
        options?: Options,
      ): Promise<AnyObject> {
        // Commented below statement until it is implemented in lb4
        // return super.execute(command, parameters, options);
        return this.dataSource.execute(command, parameters, options);
      }
    }

希望这对您的问题#1有所帮助。对于问题#2,您已经提到过这种方法。这样可行。

© www.soinside.com 2019 - 2024. All rights reserved.