我在代码中创建了以下提到的控制器,模型和存储库。请看看。
我已经开发了下面提到的代码,但是仍然无法执行联接操作。
- Info table having one foreign key which is belong to person table.
- Person table: id, name, status
- Info table : id, person_id , name , status
我还为信息和人员创建了存储库,模型和控制器文件。
人员存储库(person.repository.ts)
) {
super(Person, dataSource);
this.infos = this._createHasOneRepositoryFactoryFor(
'info',
getInfoRepository,
);
}
人员模块(person.module.ts)
@hasOne(() => Info)
infos?: Info;
constructor(data?: Partial<Person>) {
super(data);
}
信息模块(info.module.ts)
@belongsTo(() => Person)
personId: number;
constructor(data?: Partial<Info>) {
super(data);
}
它告诉我这样的错误 GET中的未处理错误/ people / fetchfromtwotable?filter [offset] = 0&filter [limit] = 10&filter [skip] = 0:500 TypeError:无法读取未定义的属性“ target”
关于加入有什么想法吗?
答案 0 :(得分:1)
drp,感谢您分享模型。我的帖子被删除了,因为我刚刚起步,需要询问更多信息,这似乎很奇怪。无论如何,请尝试更改此行:
this.infos = this._createHasOneRepositoryFactoryFor(
'info',
getInfoRepository
);
到
this.infos = this._createHasOneRepositoryFactoryFor(
'infos',
getInfoRepository,
);
该框架无法在模型上找到“信息”关系,因为您将属性称为“信息”
这是我目前可以使用的示例(运行最新的lb4和postgres):
User.model.ts
import { model, property, hasOne, Entity } from '@loopback/repository';
import { Address } from './address.model';
@model()
export class User extends Entity {
constructor(data?: Partial<User>) {
super(data);
}
@property({ id: true })
id: number;
@property()
email: string;
@property()
isMember: boolean;
@hasOne(() => Address, {})
address?: Address;
}
Address.model.ts:
import { model, property, belongsTo, Entity } from '@loopback/repository';
import { User } from '../models/user.model';
@model()
export class Address extends Entity {
constructor(data?: Partial<Address>) {
super(data);
}
@property({ id: true })
id: number;
@property()
street1: string;
@property()
street2: string;
@property()
city: string;
@property()
state: string;
@property()
zip: string;
@belongsTo(() => User)
userId: number;
}
User.repository.ts:
import { HasOneRepositoryFactory, DefaultCrudRepository, juggler, repository } from '@loopback/repository';
import { User, Address } from '../models';
import { PostgresDataSource } from '../datasources';
import { inject, Getter } from '@loopback/core';
import { AddressRepository } from '../repositories'
export class UserRepository extends DefaultCrudRepository<
User,
typeof User.prototype.id
> {
public readonly address: HasOneRepositoryFactory<Address, typeof User.prototype.id>;
constructor(
@inject('datasources.postgres')
dataSource: PostgresDataSource,
@repository.getter('AddressRepository')
protected getAccountRepository: Getter<AddressRepository>,
) {
super(User, dataSource);
this.address = this._createHasOneRepositoryFactoryFor('address', getAccountRepository);
} // end ctor
}
User.controller.ts(缩短了长度):
@get('/users/{id}/address')
async getAddress(
@param.path.number('id') userId: typeof User.prototype.id,
@param.query.object('filter', getFilterSchemaFor(Address)) filter?: Filter,
): Promise<Address> {
return await this.userRepository
.address(userId).get(filter);
}
希望这会有所帮助。
祝你好运!