I'm currently using PostgresQL with typeORM, as well as Typegraphql. With the ManyToOne
(User has many orderItems) relationship, somehow I cannot query for the nested object relation. I set the logging: true
and saw that there is no SELECT
query for the User
entity. However, I think the query should be automatically generated giving the relation I defined in the Entity according to TypeORM.
In CartItem.ts Entity
@ObjectType()
@Entity()
export class CartItem extends BaseEntity {
@PrimaryGeneratedColumn()
@Field()
id!: number;
@Column()
@Field()
userId: string;
@Field(() => User, { nullable: true })
@ManyToOne((type) => User, (user) => user.cartItems)
user: User;
In User.ts Entity
export class User extends BaseEntity {
@PrimaryGeneratedColumn("uuid")
@Field()
id!: string;
@OneToMany((type) => CartItem, (cartItem) => cartItem.user)
cartItems: CartItem[];
In cartItem.ts Resolver
@Mutation(() => CartItem)
@UseMiddleware(isAuth)
async createCartItem(
@Arg("input") input: CartItemInput,
@Ctx() { req }: MyContext
): Promise<CartItem> {
const newCart = await CartItem.create({
quantity: input.quantity,
userId: req.session.userId,
mealkitId: input.mealkitId,
}).save();
return newCart;
With the following graphql Query
, user would return null even though I'm supposed to get the username of the user
query cartItems{
cartItems {
id
quantity
userId
user{
username
}
}
}
Here is the response I received
{
"data": {
"cartItems": [
{
"id": 2,
"quantity": 2,
"userId": "5619ffb2-6ce2-42cf-bd5c-042f2685a045",
"user": null
},
{
"id": 1,
"quantity": 10,
"userId": "5619ffb2-6ce2-42cf-bd5c-042f2685a045",
"user": null
}
]
}
}```
I just ran into this myself and in my query resolver I had to leftJoinAndSelect
all of the sub-objects to get it to work. You aren't showing your query resolver, but something like
async cartItems(): Promise<CartItem[]> {
return await getConnection()
.createQueryBuilder(CartItem, 'cartItem')
.leftJoinAndSelect('cartItem.user', 'user', 'cartItem.userId = user.id')
.getMany()
}