[英]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??但它不起作用
OR
工作正常,因为我已经尝试过'users.id = 24 OR users.id = some other value
..我在这里做错了什么?
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 .一般来说,我发现通过维恩图来思考 SQL 加入是最容易的。 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.