AdminJS中HotelDescription表无法显示关联Hotel ID问题求助
解决AdminJS中HotelDescription列表不显示关联Hotel ID的问题
步骤1:修正TypeORM实体配置
你之前尝试添加@JoinColumn失败,大概率是因为没显式声明外键字段。正确做法是在HotelDescription实体中新增hotelId字段,配合@JoinColumn与@ManyToOne关联:
@Entity() export class HotelDescription extends BaseEntity { @PrimaryGeneratedColumn("uuid") id: string; @Column({ type: "text", enum: Language, nullable: true }) language: Language; @Column() name: string; @Column() description: string; @OneToOne(() => Service, (service) => service.hotelDescription) services: Service; @OneToMany(() => Treatment, (treatment) => treatment.hotelDescription) treatments: Treatment[]; // 显式声明外键字段 @Column({ type: "uuid" }) hotelId: string; @ManyToOne(() => Hotel, (hotel) => hotel.hotelDescriptions) @JoinColumn({ name: "hotelId" }) // 指定与hotelId字段关联 hotel: Hotel; }
这样TypeORM会明确生成hotelId外键列,AdminJS也能直接识别这个字段。
步骤2:配置AdminJS资源展示
根据需求选择以下两种配置方式:
方式1:直接显示hotelId字段
注册HotelDescription资源时,指定列表要展示的字段:
import AdminJS from 'adminjs'; import { Database, Resource } from '@adminjs/typeorm'; import { HotelDescription } from './entities/HotelDescription.entity'; AdminJS.registerAdapter({ Database, Resource }); const adminJs = new AdminJS({ resources: [ { resource: HotelDescription, options: { list: { properties: ['id', 'language', 'name', 'hotelId', 'description'], }, }, }, // 其他资源配置... ], });
方式2:显示关联酒店名称(更友好)
如果想展示酒店名称而非ID,可配置关联字段的展示逻辑:
const adminJs = new AdminJS({ resources: [ { resource: HotelDescription, options: { list: { properties: [ 'id', 'language', 'name', { name: 'hotelName', label: '所属酒店', sortable: true, value: (record) => record.params.hotel?.hotelName, }, 'description', ], }, // 可选:在编辑/新建页保持关联选择功能 edit: { properties: ['language', 'name', 'description', 'hotel'], }, }, }, ], });
注意事项
- 修改实体后需同步数据库(开发环境用
typeorm schema:sync,生产环境建议用迁移脚本) - 若已有历史数据,需确保
hotelId字段被正确填充,否则列表会显示空值
内容的提问来源于stack exchange,提问作者Yashar Ibra
相关产品推荐
相关产品推荐

