javascript - Inner Join 的部分选择
问题描述
我需要在现场选择一个服务,看:
async find(): Promise<AccountEntity[]> {
const result = await this.repository
.createQueryBuilder("account")
.select(['account', 'accountServices', 'service.description'])
.leftJoinAndSelect("account.accountAndServices", "accountServices")
.leftJoinAndSelect("accountServices.service", "service")
.getMany();
return result === undefined ? null : result;
}
如何 ?请。我不希望出现空属性,并且我还想选择显示我需要的属性:
{
"message": "",
"success": true,
"data": [
{
"id": 1,
"name": "STONES TECNOLOGIA LTDA",
"accountAndServices": [
{
"service": {
"name": "Construção de uma casa",
},
"date_initial": "2021-08-01T07:39:18.000Z",
"date_final": "2021-08-01T07:39:20.000Z",
"value": "10.00",
"created_by": 1,
"is_active": true,
"id": 1,
"pay_day": 10,
"nfse": 0,
"created_at": "2021-08-01T07:39:27.000Z",
},
{
"service": {
"name": "Desenvolvimento de sistemas",
},
"date_initial": "2021-08-01T07:40:01.000Z",
"date_final": "2021-08-01T07:40:02.000Z",
"value": "20.00",
"created_by": 1,
"is_active": true,
"id": 2,
"pay_day": 20,
"nfse": 0,
"created_at": "2021-08-01T07:40:11.000Z",
}
]
}
],
"errors": null
}
我只需要实体连接上的选择字段。
解决方案
使用必须使用的 innerJoin 进行选择addSelect(...)
。
find函数不能操作任何数据,并且应该返回一个数组(AccountEntity
如果没有找到则为空):
function find(): Promise<AccountEntity[]> {
return this.repository
.createQueryBuilder("a")
.innerJoin("account.accountAndServices", "as")
.innerJoin("accountServices.service", "s")
.select(['a.id', 'a.name', 'a.status'])
.addSelect(['as.date_initial', 'as.date_final', 'as.service_id', 'as.value', 'as.nfse', 'as.value', 'as.created_by', 'is_active', 'pay_day', 'created_at'])
.addSelect(['s.name'])
.getMany();
}
请注意,要从函数中获取结果,您必须使用await
. try
此外,用和包围它,catch
以便更好地处理错误。例子:
try {
const accounts: AccountEntity[] = await find();
} catch(error) {
console.error(`Error: ${error}`);
}
要将数组转换AccountEntity
为另一个对象:
function transform(accounts?: AccountEntity[]) {
return {
message: "",
success: accounts !== undefined,
data: accounts,
errors: null
};
}
推荐阅读
- assembly - 条件数据传输 VS n 条件控制传输(使用条件 mov)在 Assembly
- angular - Admanager 在 Angular 4 中的集成
- firebase - 通过rest api发送消息时如何设置通知通道?
- sql - 为什么如果我使用“=”,SQL 不会返回一个值,但如果我使用“like”会返回?
- python - 记录循环的脚本的开始和结束时间
- c++ - 时间限制超过 C++
- javascript - 转换结束后将焦点设置为 textinput
- node.js - nginx、aws 和 cloudflare 的 cors 问题
- java - 有什么方法可以将 SHA256 哈希字符串转换为 Java 字符串?
- vba - 对于仅使用时间初始化的 Date 变量,默认日期不是我所期望的