Use the "where" clause to filter records with empty parents #843
-
Hello there! I've created a @Entity()
export class Category {
@PrimaryGeneratedColumn('uuid')
uuid: string;
@Column({ unique: true })
name: string;
@ManyToOne(() => Category, (category) => category.subcategories)
parent: Category;
@OneToMany(() => Category, (category) => category.parent)
subcategories: Category[];
} I've seeded this table with several records, where some of them have no parents (i.e. a
I've managed to do this using @Injectable()
export class CategoryService {
constructor(
@InjectRepository(Category)
protected readonly categoryRepository: Repository<Category>,
) {}
static readonly PAGINATION_CONFIG: PaginateConfig<Category> = {
sortableColumns: ['name', 'subcategories.name'],
nullSort: 'last',
defaultSortBy: [['name', 'DESC']],
relations: ['subcategories', 'parent'],
loadEagerRelations: true,
maxLimit: 0,
filterableColumns: {
name: [FilterOperator.ILIKE],
'subcategories.name': [FilterOperator.ILIKE],
},
};
async findAll(query: PaginateQuery) {
return paginate(
query,
this.categoryRepository
.createQueryBuilder('bcr')
.select()
.where('bcr.parent IS NULL'),
categoryService.PAGINATION_CONFIG,
);
} This works fine. However, I'm wondering why using the // truncated
static readonly PAGINATION_CONFIG: PaginateConfig<Category> = {
where: { parent: null }, // 📌 Here I've used undefined, null, etc. How should this clause look?
sortableColumns: ['name', 'subcategories.name'],
searchableColumns: ['name', 'subcategories.name'],
nullSort: 'last',
defaultSortBy: [['name', 'DESC']],
relations: ['subcategories'],
maxLimit: 0,
filterableColumns: {
name: [FilterOperator.ILIKE],
'subcategories.name': [FilterOperator.ILIKE],
},
};
async findAll(query: PaginateQuery) {
return paginate(
query,
this.categoryRepository,
CategoryService.PAGINATION_CONFIG,
);
}
// truncated Any ideas? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Oh I just found the culprit. The // truncated
import { IsNull, Repository } from 'typeorm'; // 🫲 Import IsNull
// truncated
static readonly PAGINATION_CONFIG: PaginateConfig<Category> = {
where: { parent: IsNull() }, // 🫲 here's the solution
sortableColumns: ['name', 'subcategories.name'],
searchableColumns: ['name', 'subcategories.name'],
nullSort: 'last',
defaultSortBy: [['name', 'DESC']],
relations: ['subcategories'],
maxLimit: 0,
filterableColumns: {
name: [FilterOperator.ILIKE],
'subcategories.name': [FilterOperator.ILIKE],
},
};
async findAll(query: PaginateQuery) {
return paginate(
query,
this.categoryRepository,
CategoryService.PAGINATION_CONFIG,
);
}
// truncated Kudos to hungneox's answer on SO. |
Beta Was this translation helpful? Give feedback.
Oh I just found the culprit. The
where
clause must useIsNull()
function imported fromtypeorm
: