Querying

Relations

Load related rows with include and select, and filter by them with some, every, none, is, and isNot.

Relations are where better-drizzle saves the most repetition. Once your Drizzle relations are defined, you can load and filter by related rows with full type inference.

The examples below assume a users → posts schema with relations defined (see getting started).

Loading relations

Use include to keep the base row and attach relations:

const posts = await client.posts.findMany({
	include: { author: true },
	orderBy: [{ id: 'desc' }],
	take: 10,
});

Or select to also narrow the related fields:

const posts = await client.posts.findMany({
	select: {
		id: true,
		title: true,
		author: { select: { id: true, name: true } },
	},
});

where can constrain a row by its relations. The operators depend on the relation's cardinality.

To-one relations: is / isNot

For a "belongs to" / "has one" relation, use is (and isNot) with a nested filter:

const posts = await client.posts.findMany({
	where: {
		author: {
			is: { active: true },
		},
	},
	include: { author: true },
});

To-many relations: some / every / none

For a "has many" relation, choose the quantifier:

// Users who have at least one published post
const authors = await client.users.findMany({
	where: {
		posts: { some: { published: true } },
	},
});

// Users with no unpublished posts
const fullyPublished = await client.users.findMany({
	where: {
		posts: { none: { published: false } },
	},
});
OperatorTrue when…
someat least one related row matches
everyall related rows match
noneno related row matches
isthe single related row matches
isNotthe single related row does not match

Combining relation and scalar filters

Relation filters compose with scalar filters and logical operators like anything else:

const posts = await client.posts.findMany({
	where: {
		AND: [
			{ published: true },
			{
				author: {
					is: { email: { endsWith: '@company.com' } },
				},
			},
		],
	},
	select: {
		id: true,
		title: true,
		author: { select: { id: true, email: true } },
	},
});

Rule of thumb

  • Use where to control which rows qualify — including by their relations.
  • Use select to control which fields survive.
  • Use include to keep the full row and attach relations.

On this page