简体   繁体   中英

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[];

In general, I find it easiest to reason about SQL joins by thinking in terms of Venn Diagrams . What I gathered from your question is that we likely want something like a left inner join.

const query = this.productRepo
    .createQueryBuilder('products')
    .select()
    .leftJoin('products.users', 'user')
    .where('user.id = :id', {id: 24})
    .orWhere('user.id IS NULL')
    .getMany();

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM