繁体   English   中英

键入 Orm,其中关系是特定值或关系是 null

[英]Type Orm where relation is a specific value or relation is null

我想在一个查询中返回所有用户特定产品和一般产品(没有任何与用户映射的产品)..

我试过了

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

但它不起作用OR工作正常,因为我已经尝试过'users.id = 24 OR users.id = some other value ..我在这里做错了什么?

我的关系

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

一般来说,我发现通过维恩图来思考 SQL 加入是最容易的。 我从你的问题中收集到的是,我们可能想要类似左内连接的东西。

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

我已经通过参考这个实现了这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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