Hey there, I'm diving into the world of TypeORM and could really use some guidance.
I've been attempting to set up many-to-many relationships with custom properties following the instructions provided here
However, I've run into a few issues along the way.
The desired query result looks like this..
{
"id": 1,
"username": "John Doe",
"products": [
{
"id": 1,
"title": 'A shirt',
"description": 'lorem ipsum'
}
]
}
But unfortunately, the actual result is...
{
"id": 1,
"username": "John Doe",
"products": [
{
"id": 1,
"userId": 1,
"productId":1
}
]
}
This is how I'm currently querying
const user = await this.userRepository.findOne({
where: { id },
relations: ["products"],
});
Here is the code breakdown:
UserProduct Entity
// user-product.entity.ts
@Entity()
export class UserProduct extends BaseEntity {
@PrimaryColumn()
public id: number;
@Column()
public userId!: number;
@Column()
public productId!: number;
@ManyToOne(
() => User,
(user) => user.products
)
public user!: User;
@ManyToOne(
() => Product,
(product) => product.users
)
public product!: Product;
}
User Entity
// user.entity.ts
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@OneToMany(()=> UserProduct, userToProduct => userToProduct.user)
public products!: UserProduct[];
}
Product Entity
// product.entity.ts
@Entity()
export class Product extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column({ nullable: true })
subtitle: string;
@Column({ nullable: true })
description: string;
@OneToMany(
() => UserProduct,
(userProduct) => userProduct.product
)
public users!: UserProduct[];
}
If you have any insights on achieving the desired query result, please share your thoughts!