Hi! How do you guys store images in the database? ...
# orm-help
d
Hi! How do you guys store images in the database? I have this model here that seems perfect, but if I wanna use it in (for example) 10 different models I would have to make a relation for every model which seems kinda annoying. An alternative would be to just store something like "imageId" in the user model (or basically any model that needs to have an image) and since I'm using graphql it wouldn't be as much of an issue. Does my solution seem good?
Copy code
model Image {
  id Int @id @default(autoincrement())

  publicId String
  width    Int
  height   Int
  url      String

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}
1
a
Why it’s a problem for you to have 10 relations? Our user model has over 100 relations to other models because of creator and updater infos. That’s absolutely not a big deal.
d
I thought maybe it wasn't optimal, wasn't really sure
Thanks!
a
Since it’s a kind of “virtual” field (i mean the relation). It’s fetched only if you select it. In other cases it doesn’t have any performance side effects.
h
Hey Idan 👋 If you wanted to store an image in a database, you could store it as a Base64 which I do not recommend. If you're using a social login, you can store the URL of the avatar of the user. Now, if you have your own login form, things get slightly more complicated. You'll have to setup an image CDN to host your images, and then save the link to that in your database. If you need suggestions for which CDN to use, I can suggest some paid and unpaid ones which I've personally used 😄
👍 1
n
Ideally, you should store images on a Blob Store like AWS S3 or other CDNs like Cloudinary and just store the reference of the resource in your model. Encoding Image into base64 while storing and again decoding at the client while displaying would be expensive.
🙌 1
a
@Nurul I would say it depends on the use case. For small avatar images that’s much easier to store those directly in the DB. But i would prefer to use a binary filed for that.
We have implemented a document management software for our client. He wants to have that on premise. So it was not possible to use services like S3. We just used the binary typed field of Postgres. That works very well! We have over 150K documents with total amount of size over 120 GB! And it works very well in the production. We have no performance issues.
n
That’s true, if the image size is small, you can definitely store it in the database. It all depends on the use case.
d
For the small code example I sent, I'm using cloudinary. The reason I'm saving the data in it's own model is because I need to store more data about the image than just the url
👍 1
c
You are using a relational database so relations are not a problem.