我正在尝试用新的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,
);
}
}
例如,当我执行get-on-orders时,会出现错误:
500 error: column "products" does not exist
并且在进一步挖掘时,我可以看到sql正试图检索字段products
,其中它只是一个关系。有人知道我做错了什么吗?
我使用pg作为db。
最佳答案
我相信这是环回4的一个漏洞。当用@hasMany
修饰类属性时,decorator会在hood下定义一个model属性。见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跟踪,请考虑对该问题进行投票并加入讨论。
关于postgresql - 回送4-字段中包含HasMany关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52931333/