我正在尝试使用新的Loopback 4框架设置关系HasMany。 我有以下模型:
import {Entity, model, property, belongsTo, hasMany} from
'@loopback/repository';
import {User} from "./user.model";
import {OrderProduct} from "./order-product.model";
@model({
name: 'sales_order'
})
export class Order extends Entity {
@property({
type: 'number',
id: true,
required: true,
})
id: number;
@property({
type: 'number',
required: true,
})
total_amount: number;
@belongsTo(() => User)
user_id: number;
@hasMany(() => OrderProduct, {keyTo: 'order_id'})
products?: OrderProduct[];
constructor(data?: Partial<Order>) {
super(data);
}
}
存储库如下:
import {DefaultCrudRepository, repository, HasManyRepositoryFactory, BelongsToAccessor} from '@loopback/repository';
import {Order, OrderProduct, User} from '../models';
import {DbDataSource} from '../datasources';
import {inject, Getter} from '@loopback/core';
import {OrderProductRepository} from "./order-product.repository";
import {UserRepository} from "./user.repository";
export class OrderRepository extends DefaultCrudRepository<
Order,
typeof Order.prototype.id
> {
public readonly user: BelongsToAccessor<
User,
typeof Order.prototype.id
>;
public readonly products: HasManyRepositoryFactory<
OrderProduct,
typeof Order.prototype.id
>;
constructor(
@inject('datasources.db') dataSource: DbDataSource,
@repository.getter(OrderProductRepository)
getOrderProductRepository: Getter<OrderProductRepository>,
@repository.getter('UserRepository')
userRepositoryGetter: Getter<UserRepository>,
) {
super(Order, dataSource);
this.products = this._createHasManyRepositoryFactoryFor(
'products',
getOrderProductRepository,
);
this.user = this._createBelongsToAccessorFor(
'user_id',
userRepositoryGetter,
);
}
}
例如,当我接受订单时,出现错误:500 error: column "products" does not exist
,并且在进行更多挖掘时,我看到SQL正在尝试检索字段products
所在的位置只是一种关系。
有人知道我做错了什么吗?
我正在使用pg作为数据库。
答案 0 :(得分:0)
我相信这是LoopBack 4中的错误。当您用@hasMany
装饰类属性时,装饰器在后台定义了模型属性。参见here:
export function hasMany<T extends Entity>(
targetResolver: EntityResolver<T>,
definition?: Partial<HasManyDefinition>,
) {
return function(decoratedTarget: Object, key: string) {
property.array(targetResolver)(decoratedTarget, key);
// ...
};
}
当连接器查询数据库时,它试图在查询中包括列products
,因为它认为products
是属性。
https://github.com/strongloop/loopback-next/issues/1909已跟踪了该问题,请考虑对问题进行投票并加入讨论。