我试图实现一种方法来过滤具有ManytoMany关系的表中的数据。
我有以下表格job,job_category和category。
到目前为止,我正在考虑使用job_id对job_category进行查询,然后使用该结果使用IN()添加条件,但我也没有找到任何方法来实现此选项。
问题:
PD我可以使用$ inq来回答问题2。
filter.where = {
...filter.where,
id: {inq: [2, 7]},
};
根据您的问题的上下文,可以在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控制器或存储库类来实现此目的。我的两个建议方法如下。
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,您已经提到过这种方法。这样可行。