Become a Gold Sponsor
Drizzle | 查询中的条件过滤器
PostgreSQL
MySQL
SQLite
This guide assumes familiarity with:

要在查询中传递条件过滤器,可以使用 .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
  );

如果你需要在项目的不同地方组合条件过滤器,可以创建一个变量,推入过滤器,然后在 .where() 方法中使用 and()or() 运算符,如下所示:

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';

// 长度小于
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 是内部魔法函数
};