Easiest way to add an array of objects?
Hey, I am trying to add an array of objects to my schema with postgres, how can I do this? there seems to be a pgArray but can't find a pgObject 👀
export const products = pgTable("products", {
id: serial("id").primaryKey().unique(),
description: text("description").notNull(),
details: text("details").notNull(),
price: numeric("price").notNull(),
images: array(
pgObject({
title: text("title").notNull(),
tag: text("tag").notNull(),
imageUrl: text("imageUrl").notNull(),
}),
),
});
3 Replies
There is no such thing as pgObject in drizzle
Can you show how you would do this in plain sql?
I just did a quick search and Bard spat that out and assumed it was a feature 😂
For example here, import { InferSelectModel, relations } from "drizzle-orm";
import {
pgTable,
serial,
text,
timestamp,
numeric,
integer,
} from "drizzle-orm/pg-core";
export const users = pgTable("users", {
id: serial("id").primaryKey(),
name: text("name").notNull(),
email: text("email").notNull(),
image: text("image").notNull(),
clerkId: text("clerkId").notNull().unique(),
stripeCustomer: text("stripeCustomer").notNull().unique(),
createdAt: timestamp("createdAt").defaultNow().notNull(),
});
export const products = pgTable("products", {
id: serial("id").primaryKey(),
description: text("description").notNull(),
details: text("details").notNull(),
price: numeric("price").notNull(),
authorId: integer("author_id"),
title: text("title").notNull(),
subtitle: text("subtitle").notNull(),
tags: ["journal", "cheap"],
});
export const productVariant = pgTable("productVariant", {
id: serial("id").primaryKey(),
image: text("image").notNull(),
color: text("color").notNull(),
variantName: text("variantName").notNull(),
authorId: integer("author_id"),
postId: integer("post_id"),
});
export const productVariantRelations = relations(productVariant, ({ one }) => ({
product: one(products, {
fields: [productVariant.postId],
references: [products.id],
}),
}));
export const userRelations = relations(users, ({ many }) => ({
products: many(products),
}));
export const productRelations = relations(products, ({ one, many }) => ({
author: one(users, {
fields: [products.authorId],
references: [users.id],
}),
productVariant: many(productVariant),
}));
export type Products = InferSelectModel<typeof users>;
export type User = InferSelectModel<typeof users>;
I am trying to create some sort of tag system that just holds string primites in an array, is it worth creating a seperate schema for this do you reckon?
If you are not planning to use tags to search for stuff then that should be fine
And even then, if your table is short enough, a search with tags in an array should be fast enough