3 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超2個(gè)贊
您可以將此部分添加到您的實(shí)體中:
fullName: string; // just define a property to use it in afterLoad method
@AfterLoad() // this method will be called on each entity query
afterLoad() {
this.fullName = `${this. firstName} ${this.lastName}`;
}

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
@Entity()
export class User {
@PrimaryGeneratedColumn()
id!: number;
@Column({
type: 'varchar',
})
firstName: string;
@Column({
type: 'varchar',
})
lastName: string;
@Expose()
public get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
執(zhí)行上述操作時(shí),數(shù)據(jù)庫(kù)不會(huì)將 fullName 值存儲(chǔ)在列中。相反,它是在每次訪問(wèn)時(shí)即時(shí)計(jì)算的。

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以創(chuàng)建一個(gè)代表最終數(shù)據(jù)的類型,例如:
type CustomUser = {
id: number;
firstName: string;
lastName: string;
fullName: string;
}
之后,讓您的查詢返回此類型
return getManager()
.createQueryBuilder(User, 'user')
.select('user.id', 'id')
.select('user.firstName', 'firstName')
.addSelect('user.lastName', 'lastName')
.addSelect('CONCAT(firstName, ' ', lastName', 'fullName')
.getRawMany();
// getRawMany() if you want to fetch many records or getRawOne()
如果您只需要所有用戶的 fullName 列,您可以嘗試:
const { fullName } = await getManager()
.createQueryBuilder(User, 'user').select('CONCAT(firstName, ' ',
lastName', 'fullName').getRawMany();
return fullName;
添加回答
舉報(bào)