I have this entity in nestjs
@Entity("mytable")
export class MyEntity extends CommonEntity {
@ManyToOne(() => Entity2)
@JoinColumn({ name: "entity_id", referencedColumnName: "id" })
@IsInt()
@IsNotEmpty()
entityId: number;
@Column({ name: "user_id", type: "integer", select: false })
@IsNotEmpty()
userId: number;
@ManyToOne(() => UserEntity) // Establish Many-to-One relationship
@JoinColumn({ name: 'user_id', referencedColumnName: 'id' }) // Specify the join column
userInfo: UserEntity;
}
i want the response as
[
{
entityId, userInfo
}, {...}
]
entityId
and the userInfo
based on list of entityIds
for this I am writing this query
async _getUsersForEntities(entityIds: number[]): Promise<MyEntity[]> {
return this.myRepository.find({
select: [ "entityId", "userInfo"],
where: {
entityId: In(entityIds),
},
relations: ['userInfo'],
});
}
but select
is not working it is returning all the fields instead of entityId like this
{
id: 31,
createdAt: 2023-10-11T14:34:50.446Z,
status: 'Active',
userInfo: UserEntity {
id: 3,
createdAt: 2023-10-06T13:51:19.232Z,
status: 'Active',
imgUrl: null,
name: 'helo'
}
}
how can i fix this. I need entityId
along with userInfo
You use @JoinColumn
incorrectly at entityId: number;
. JoinColumn
is meant for fields that are supposed to contain the entity's object to which the join is going to happen, and the name
field in @JoinColumn({ name: '...' })
should point to the column where the id of related entity is stored. Essentially it's the same thing you did with userInfo
and userId
.
So the solution is:
@Entity("mytable")
export class MyEntity extends CommonEntity {
@Column({ name: "entity_id", type: "integer" })
@IsInt()
@IsNotEmpty()
entityId: number; // <- store the id of the referenced entity in a separate field.
// also make sure that you have this `entity_id` column in your database.
@ManyToOne(() => Entity2)
@JoinColumn({ name: "entity_id", referencedColumnName: "id" }) // <- point to the field where the id of related entity is stored
entity: Entity2;
...
// and then this select should do the job
async _getUsersForEntities(entityIds: number[]): Promise<MyEntity[]> {
return this.myRepository.find({
select: [ "entityId", "userInfo"],
where: {
entityId: In(entityIds),
},
relations: ['userInfo'],
});
}