我的用戶擁有一家或多家公司。每家公司都可以有一個或多個辦事處。我想根據連接的用戶通過其 ID 檢索與公司鏈接的辦公室串列。
我在下面的代碼中所做的是,我通過用戶的自定義裝飾器來檢索登錄的用戶。然后我檢索這些公司,然后檢索辦公室。但是,我無法檢索用戶的公司。我有這個錯誤,因為在用戶中,沒有公司財產。
[Nest] 59645 - 09/05/2022, 00:28:18 錯誤 [ExceptionsHandler] 無法讀取未定義的屬性(讀取“查找”)型別錯誤:無法讀取 OfficeRepository.getOffices 中未定義的屬性(讀取“查找”)(/用戶/ismaelmohamed/Documents/projects/melivy_projects/melivy_api/src/office/office.repository.ts:16:40) 在 processTicksAndRejections (node:internal/process/task_queues:96:5)
我有點迷茫,知道嗎?
我的代碼
// office.repository.ts
async getOffices(companyId: string, user: User): Promise<Office[]> {
const query = this.createQueryBuilder('office');
query.where('office.companyId = :companyId', { companyId });
console.log(user);
if (user) {
const companies = await user.companies;
const currentCompany = companies.find(
(company) => company.id === companyId,
);
if (currentCompany) {
query.andWhere('office.id IN (:...officeIds)', {
officeIds: currentCompany.offices.map((office) => office.id),
});
}
}
return await query.getMany();
}
// office.service.ts
async getOffices(companyId: string, user: User): Promise<Office[]> {
return this.officeRepository.getOffices(companyId, user);
}
// office.controller.ts
async getOffices(
@Param('id') id: string,
@GetUser() user: User,
): Promise<Office[]> {
return this.officeService.getOffices(id, user);
}
// get-user.decorator.ts
export const GetUser = createParamDecorator(
(data: string | undefined, ctx: ExecutionContext) => {
const request: Express.Request = ctx.switchToHttp().getRequest();
if (data) {
return request.user[data];
}
return request.user;
},
);
uj5u.com熱心網友回復:
我建議您通過帶有 User 的 userId 的查詢構建器來搜索公司,而不是嘗試直接從 get-user 裝飾器中獲取公司。
const companies_query = this.createQueryBuilder('companies');
companies_query.where('companies.user_id = :user_id', { user.id });
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/472040.html
上一篇:二級鍵作為型別
