Conditional Relational Queries

I have these tables Simplified Version

export const ingredientTypeEnum = pgEnum('ingredientType', ['ITEM', 'FOOD']);

export const food = pgTable('food', {
    id: serial('id').primaryKey(),
    name: varchar('name', { length: 256 }).notNull(),
});

export const item = pgTable('item', {
    id: serial('id').primaryKey(),
    name: varchar('name', { length: 256 }).notNull(),
    description: text('description').array(),
});

export const ingredient = pgTable('ingredient', {
    recipe_id: integer('recipe_id').references(() => recipe.id),
    ingredientType: ingredientTypeEnum('ingredientType'),
    quantity: integer('amount').notNull(),
});

export const recipe = pgTable('recipe', {
    id: serial('id').primaryKey(),
    name: varchar('name', { length: 256 }).notNull(),
    instructions: text('description').array(),
});

export const recipeRelations = relations(recipe, ({ many }) => ({
    ingredients: many(ingredient),
}));


Is it possible to setup the table relationships so that depending on the ingredient type it utilizes the corresponding tables?

For example, with an ingredient type of ITEM it would use the item table instead of the food table.
Was this page helpful?