Drizzle 查询 + CRUD
Drizzle 提供了几种查询数据库的方法,您可以根据下一个项目的需要选择合适的方式。
它可以是类似 SQL 的语法或关系语法。让我们来看看它们:
Why choose SQL-like syntax?
If you know SQL, you can master Drizzle.
Other ORMs and data frameworks often deviate from or abstract away SQL, which creates a double learning curve: you need to learn both SQL and the framework’s API.
Drizzle is the opposite. We embrace SQL and build Drizzle’s core in a SQL-like form, so that you have almost no learning curve and can fully leverage the power of SQL.
// Access your data
await db
.select()
.from(posts)
.leftJoin(comments, eq(posts.id, comments.post_id))
.where(eq(posts.id, 10))SELECT *
FROM posts
LEFT JOIN comments ON posts.id = comments.post_id
WHERE posts.id = 10With SQL-like syntax, you can do most of what you can do in plain SQL, and clearly know what Drizzle will execute and what queries it will generate. You can perform a variety of queries, including select, insert, update, delete, as well as aliases, WITH clauses, subqueries, prepared statements, and more. Let’s look at more examples.
await db.insert(users).values({ email: 'user@gmail.com' })INSERT INTO users (email) VALUES ('user@gmail.com')为什么不选择 SQL 类似语法?
我们始终在追求一个完美平衡的解决方案。虽然 SQL 类似查询可以满足 100% 的需求, 但在某些常见场景中,数据的查询可以更高效。
我们构建了查询 API,以便你可以以最方便和高效的方式从数据库中获取关系型、嵌套数据, 而无需担心联接或数据映射。
Drizzle 总是输出确切的一个 SQL 查询。可以放心地与无服务器数据库一起使用, 而无需担心性能或往返成本!
const result = await db.query.users.findMany({
with: {
posts: true
},
});高级
使用 Drizzle,查询可以以你想要的任何方式组合和分区。 你可以独立于主查询组合过滤器,分离子查询或条件语句,等等。 让我们来看几个高级示例:
组合一个 WHERE 语句,然后在查询中使用它
async function getProductsBy({
name,
category,
maxPrice,
}: {
name?: string;
category?: string;
maxPrice?: number;
}) {
const filters: SQL[] = [];
if (name) filters.push(ilike(products.name, name));
if (category) filters.push(eq(products.category, category));
if (maxPrice) filters.push(lte(products.price, maxPrice));
return db
.select()
.from(products)
.where(and(...filters));
}将子查询分离到不同变量中,然后在主查询中使用它们
const subquery = db
.select()
.from(internalStaff)
.leftJoin(customUser, eq(internalStaff.userId, customUser.id))
.as('internal_staff');
const mainQuery = await db
.select()
.from(ticket)
.leftJoin(subquery, eq(subquery.internal_staff.userId, ticket.staffId));