Drizzle | 查询中的条件筛选
PostgreSQL
MySQL
SQLite
要在查询中传递条件筛选,您可以使用 .where()
方法和逻辑运算符,如下所示
import { ilike } from 'drizzle-orm';
const db = drizzle(...)
const searchPosts = async (term?: string) => {
await db
.select()
.from(posts)
.where(term ? ilike(posts.title, term) : undefined);
};
await searchPosts();
await searchPosts('AI');
select * from posts;
select * from posts where title ilike 'AI';
要组合条件筛选,您可以使用 and()
或 or()
运算符,如下所示
import { and, gt, ilike, inArray } from 'drizzle-orm';
const searchPosts = async (term?: string, categories: string[] = [], views = 0) => {
await db
.select()
.from(posts)
.where(
and(
term ? ilike(posts.title, term) : undefined,
categories.length > 0 ? inArray(posts.category, categories) : undefined,
views > 100 ? gt(posts.views, views) : undefined,
),
);
};
await searchPosts();
await searchPosts('AI', ['Tech', 'Art', 'Science'], 200);
select * from posts;
select * from posts
where (
title ilike 'AI'
and category in ('Tech', 'Science', 'Art')
and views > 200
);
如果您需要在项目的不同部分组合条件筛选,您可以创建一个变量,添加筛选条件,然后将其与 and()
或 or()
运算符一起在 .where()
方法中使用,如下所示
import { SQL, ... } from 'drizzle-orm';
const searchPosts = async (filters: SQL[]) => {
await db
.select()
.from(posts)
.where(and(...filters));
};
const filters: SQL[] = [];
filters.push(ilike(posts.title, 'AI'));
filters.push(inArray(posts.category, ['Tech', 'Art', 'Science']));
filters.push(gt(posts.views, 200));
await searchPosts(filters);
Drizzle 具有实用且灵活的 API,可让您创建自定义解决方案。以下是如何创建自定义筛选运算符的方法
import { AnyColumn, ... } from 'drizzle-orm';
// length less than
const lenlt = (column: AnyColumn, value: number) => {
return sql`length(${column}) < ${value}`;
};
const searchPosts = async (maxLen = 0, views = 0) => {
await db
.select()
.from(posts)
.where(
and(
maxLen ? lenlt(posts.title, maxLen) : undefined,
views > 100 ? gt(posts.views, views) : undefined,
),
);
};
await searchPosts(8);
await searchPosts(8, 200);
select * from posts where length(title) < 8;
select * from posts where (length(title) < 8 and views > 200);
Drizzle 筛选运算符在底层只是 SQL 表达式。这是 lt
运算符在 Drizzle 中如何实现的示例
const lt = (left, right) => {
return sql`${left} < ${bindIfParam(right, left)}`; // bindIfParam is internal magic function
};