Defining nested types with Drizzle Zod

What would be the correct way to create nested types with drizzle-zod here?

I have an acccount table like this:

import { pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { townhall } from "./townhall";

export const account = pgTable("account", {
  ID: uuid().defaultRandom().primaryKey().notNull(),
  createdAt: timestamp({
    withTimezone: true,
    mode: "string",
  })
    .defaultNow()
    .notNull(),
  updatedAt: timestamp({
    withTimezone: true,
    mode: "string",
  })
    .defaultNow()
    .$onUpdate(() => new Date().toISOString())
    .notNull(),
  username: text().notNull(),
  townhallID: uuid()
    .references(() => townhall.ID)
    .notNull(),
});



And a townhall table like this:

import { integer, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";

export const townhall = pgTable("townhall", {
  ID: uuid().defaultRandom().primaryKey().notNull(),
  createdAt: timestamp({
    withTimezone: true,
    mode: "string",
  })
    .defaultNow()
    .notNull(),
  updatedAt: timestamp({
    withTimezone: true,
    mode: "string",
  })
    .defaultNow()
    .$onUpdate(() => new Date().toISOString())
    .notNull(),
  level: integer().unique("townhall_level_unique").notNull(),
  color: text().notNull(),
});



How can I make sure the type comes back like this? That's the type I receive from my query and I need it to define my tanstack-table columns

Account = {
  id: string;
  username: string;
  townhall: {
    id: string;
    level: number;
    color: string;
  };
};


I have the omit part down:

import { createSelectSchema } from "drizzle-zod";
import { account } from "@/db/schema/account";

const selectAccountSchema = createSelectSchema(account).omit({
  createdAt: true,
  updatedAt: true,
});

export type Account = typeof selectAccountSchema._type;
Was this page helpful?