Search code examples
node.jsnestjstypeormnode.js-typeorm

Type Orm where relation is a specific value or relation is null


I want to return all user specific products and general products ( products without any have any mapping with users) in one query ..

I have tried

const query = this.productRepo
        .createQueryBuilder('products')
        .innerJoinAndSelect('products.users',
         'users',
        'users.id = 24 OR users.id IS NULL'
        )....more

But it's not working the OR is working fine because i have tried 'users.id = 24 OR users.id = some other value which is working fine.. what I have done wrong here??

My relation

@ManyToMany(() => User, {
    onUpdate: 'CASCADE',
    onDelete: 'CASCADE',
    nullable: true,
})
@JoinTable({
    name: 'product_user_mappings',
    joinColumn: {
        name: 'productId',
        referencedColumnName: 'id',
    },
    inverseJoinColumn: {
        name: 'userId',
    },
})
users: User[];

Solution

  • I have implemented this by referring this

    const where = {
                isActive: true,
                volume: MoreThan(0),
                priceValidity: MoreThan(new Date()),
            };
    
        const query = this.productRepo
        .createQueryBuilder('products')
        .select()
        .leftJoin('products.users', 'user')
        .where(where)
        .andWhere(new Brackets(qb => {
                    qb.where('users.id = :userId', { userId: user.id })
                    qb.orWhere('users.id is null')
                }))
        .getMany()