Creating database model - synthofficial/discord-idle-game-bot-template GitHub Wiki

Creating a Database Model

A Prisma model represents a table in your database. Each model maps to a table and defines the structure of your data.

Basic Example

Here's a simple User model for an idle game:

model User {
  userId     String @id @unique
  level      Int    @default(1)
  experience Int    @default(0)
  money      Int    @default(1000)

  @@map("users") // This is how the table will be named in your database
}

Understanding the Fields

  • userId - Unique identifier for each user (using Discord user ID)

    • String - Data type
    • @id - Primary key
    • @unique - Ensures no duplicates
  • level, experience, money - Game stats

    • Int - Integer data type
    • @default() - Sets initial values when creating a new user
  • @@map("users") - Names the actual database table as "users"

๐Ÿ“ Organizing Multiple Models

For larger projects, you can split your models into separate files inside a schema/ folder:

โ”œโ”€โ”€ src/
โ”œโ”€โ”€ prisma/
โ”‚   โ”œโ”€โ”€ schema.prisma
โ”‚   โ”œโ”€โ”€ schema/
โ”‚   โ”‚   โ”œโ”€โ”€ user.prisma
โ”‚   โ”‚   โ”œโ”€โ”€ guild.prisma
โ”‚   โ”‚   โ”œโ”€โ”€ inventory.prisma
โ”‚   โ”‚   โ””โ”€โ”€ tools.prisma

Importing Schema Files

In your main schema.prisma file, import the separate schema files:

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql" # This can be changed to "mysql"
  url      = env("PRISMA_URL")
}

// Import your models
import "schema/user.prisma"
import "schema/guild.prisma"
import "schema/inventory.prisma"
import "schema/tools.prisma"

Note: This keeps your codebase clean and makes it easier to manage multiple models!

Common Field Types

Type Description Example Use
String Text data User IDs, names
Int Whole numbers Level, experience, money
Boolean True/false Premium status, banned
DateTime Date and time Created at, last active
Float Decimal numbers Multipliers, percentages

๐Ÿ”„ After Creating Your Model

Once you've created or modified your models, run:

๐Ÿ“ฆ npm / npx
npm run db:gen  # Generate Prisma Client
npm run db:push   # Push changes to your database
๐ŸฅŸ Bun
bun db:gen  # Generate Prisma Client
bun db:push   # Push changes to your database
๐Ÿ“ฆ pnpm
pnpm db:gen  # Generate Prisma Client
pnpm db:push   # Push changes to your database
๐Ÿงถ Yarn
yarn db:gen  # Generate Prisma Client
yarn db:push   # Push changes to your database
โš ๏ธ **GitHub.com Fallback** โš ๏ธ