πŸ”§ Error Fixes
Β· 1 min read

Drizzle ORM: Relation Not Found β€” How to Fix It


Error: Relation not found

Drizzle can’t find the relation you defined.

Why this happens

Drizzle ORM separates table definitions from relation definitions. Relations are defined using the relations() helper and must be explicitly passed to the drizzle() client via the schema option. If you forget to define the relation, define it incorrectly, or don’t pass the schema object to the client, Drizzle has no way to resolve relational queries and throws this error.

Fix 1: Define relations correctly

import { relations } from 'drizzle-orm';

export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name'),
});

export const posts = pgTable('posts', {
  id: serial('id').primaryKey(),
  authorId: integer('author_id').references(() => users.id),
});

// βœ… Define relations separately
export const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
}));

export const postsRelations = relations(posts, ({ one }) => ({
  author: one(users, { fields: [posts.authorId], references: [users.id] }),
}));

Fix 2: Pass relations to drizzle()

import * as schema from './schema';
const db = drizzle(client, { schema });

Alternative solutions

If you don’t need Drizzle’s relational query API, you can skip relation definitions entirely and use manual joins instead:

const result = await db
  .select()
  .from(posts)
  .leftJoin(users, eq(posts.authorId, users.id));

Also make sure all your relation and table definitions are exported from the same schema file (or re-exported from a barrel file) so the import * as schema picks up everything.

Prevention

  • Always pass { schema } to the drizzle() constructor when you plan to use relational queries β€” this is easy to forget when setting up a new project.
  • Keep all table and relation definitions in a single schema.ts file (or use a barrel index.ts) so nothing gets missed during the import.

Related: Drizzle ORM: Type Error β€” Column Type Mismatch Β· Prisma vs Drizzle vs TypeORM