Setup a database model in Blitzjs

Khaled Garbaya
InstructorKhaled Garbaya

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 4 months ago

By default, Blitz uses Prisma 2 which is a strongly typed database client.

Prisma 2 is not required for Blitz. You can use anything you want, such as Mongo, TypeORM, etc.

To add a Database Table you need to add a model to your db/shcema.prisma file.


model Post {
  id   Int  @default(autoincrement()) @id
  slug String @unique
  title String
  content String

Then run blitz db migrate. the cli will prompt you to name the migration, give it any name you want, and confirm.

After the migration is done you can explore your DB tables using blitz db studio.

For local development using sqlite is very convenient as it is basically a file and it does not require any extra setup.

Khaled Garbaya: [0:00] First, let's open up our schema.prisma file. You can find that inside of db and then schema.prisma. Here, we're going to define our new model. Let me just delete this commented one and type in model and we want a model of Post.

[0:20] Our post will have an id. This is of type Int, and it's going to be @default(autoincrement). We can assign the id to it. We will have also slug of type String, and we will set it as @unique. We'll have also a title, which is of type String and content, which would be String also.

[0:41] Let's save this. Now, let's open up our console and then call blitz db migrate, and hit Enter. You can see here Blitz is asking us for the name of this migration. We can call it @Postmodel. You can see here it applied the migration.

[0:59] We can explore our database using blitz db studio. To launch that, we need to do blitz db, and then studio. It will start here, blitz studio. You can see here that we have our post model that we just created, and it has id, slug, title and also content.

[1:23] We can go ahead and add the record here. This will be by default as autoincrement. Here, we can type in "Hello World." The title will be "Hello World." For the content, it's going to be "some content." If we hit Save, you can see here we have created our first record.