[英]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.