0Pricing
Next.js 15 Fullstack Web Apps · บทเรียน

การดำเนินการ CRUD ด้วย Prisma Client

ดำเนินการสร้าง อ่าน อัปเดต และลบข้อมูลโดยใช้ Prisma Client ที่ปลอดภัยด้านชนิดข้อมูล

การดำเนินการ CRUD ด้วย Prisma Client เป็นบทเรียน Next.js 15 Fullstack Web Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Next.js 15 Fullstack Web Apps และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Intro to CRUD with Prisma

Welcome! In this lesson, we'll master CRUD operations using Prisma Client. CRUD stands for Create, Read, Update, and Delete – the four fundamental operations for interacting with any database.

Prisma Client provides a type-safe and intuitive way to perform these actions, making your database interactions efficient and less error-prone.

Instantiating Prisma Client

Before performing any database operations, you need to instantiate the Prisma Client. This client is automatically generated based on your schema.prisma file and connects your application to the database.

You'll typically do this once in your application's entry point or a dedicated database module.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  console.log('Prisma Client initialized!');
  // Database operations go here
}

main()
  .catch(e => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Create: Adding New Data

The Create operation adds new records to your database. With Prisma, you use the create method on a model to insert data.

  • Specify the model (e.g., prisma.user).
  • Provide the data for the new record in the data object.
  • Prisma handles the SQL insertion for you!

Remember, this assumes you have a User model defined in your schema.prisma.

Create: Adding a User Record

Let's create a new User record. Notice how Prisma Client provides autocompletion for fields like email and name, ensuring type safety.

Run this example to see a new user being added.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  console.log('Creating a new user...');
  const newUser = await prisma.user.create({
    data: {
      email: 'alice@example.com',
      name: 'Alice Smith',
    },
  });
  console.log('Created user:', newUser.name, 'with ID:', newUser.id);
}

main()
  .catch(e => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Read: Fetching Multiple Records

The Read operation retrieves data. To fetch multiple records, use the findMany method. You can filter results using the where clause, order them with orderBy, or limit them with take.

For example, prisma.user.findMany({ where: { name: 'Alice Smith' } }) would find all users named Alice Smith.

Read: Fetching Single Records

To fetch a single, unique record, use findUnique. This method requires a unique identifier (like an @id or @unique field in your schema) to ensure only one record is returned.

If you need to find the first record matching a non-unique condition, use findFirst. It returns null if no record is found.

Read: Users from the Database

Let's fetch all users and then find a specific user by their email using findUnique. This demonstrates how to retrieve both lists and individual items.

Run the code to see the results of these queries.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  console.log('Fetching all users...');
  const allUsers = await prisma.user.findMany();
  console.log('All users:', allUsers.map(u => u.name).join(', '));

  console.log('Finding user by unique email...');
  const alice = await prisma.user.findUnique({
    where: {
      email: 'alice@example.com',
    },
  });
  if (alice) {
    console.log('Found Alice:', alice.name);
  } else {
    console.log('Alice not found.');
  }
}

main()
  .catch(e => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Update: Modifying Existing Data

The Update operation changes existing records. The update method requires two main parts:

  • A where clause to identify the record(s) to update.
  • A data object containing the fields and new values to set.

Always ensure your where clause is specific enough to avoid unintended updates!

Update: Changing a User's Name

We'll update the user 'Alice Smith' to 'Alicia Wonderland'. Notice how we target the user with their unique email and then provide the new name.

After running, you can try fetching Alice again to see the updated name.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  console.log('Updating user Alice Smith...');
  const updatedUser = await prisma.user.update({
    where: {
      email: 'alice@example.com',
    },
    data: {
      name: 'Alicia Wonderland',
    },
  });
  console.log('Updated user:', updatedUser.email, 'now named:', updatedUser.name);
}

main()
  .catch(e => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Delete: Removing Data

Finally, the Delete operation removes records from your database. The delete method, like update, requires a where clause to specify which record(s) to remove.

Be cautious with delete operations, as they are permanent! Always double-check your where condition.

CRUD Operations Check

Which Prisma Client method would you use to remove a specific user record from the database?

Recap: CRUD with Prisma

Great job! You've learned the core of database interaction using Prisma Client.

  • Create (C): Use prisma.model.create() to add new records.
  • Read (R): Use prisma.model.findMany() for lists, findUnique() or findFirst() for single records.
  • Update (U): Use prisma.model.update() to modify existing records.
  • Delete (D): Use prisma.model.delete() to remove records.

Prisma's type safety and intuitive API make these essential operations straightforward and robust in your Next.js applications.

คำถามที่พบบ่อย

บทเรียน “การดำเนินการ CRUD ด้วย Prisma Client” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การดำเนินการ CRUD ด้วย Prisma Client” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack Web Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การดำเนินการ CRUD ด้วย Prisma Client”

ดำเนินการสร้าง อ่าน อัปเดต และลบข้อมูลโดยใช้ Prisma Client ที่ปลอดภัยด้านชนิดข้อมูล คุณปฏิบัติ Next.js 15 Fullstack Web Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack Web Apps หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack Web Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การดำเนินการ CRUD ด้วย Prisma Client” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack Web Apps นี้ได้ไหม

ได้ บทเรียน Next.js 15 Fullstack Web Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. แนะนำ Prisma ORM
  2. การออกแบบสคีมา Prisma และการย้ายข้อมูล
  3. การดำเนินการ CRUD ด้วย Prisma Client
  4. ความสัมพันธ์และคำค้นขั้นสูงด้วย Prisma
← กลับไปที่ Next.js 15 Fullstack Web Apps