keyboard_tabSkip to content
listGoAPI Essential

แนะนำ GORM

สารบัญ

พื้นฐาน CRUD ใน GORM

Ref: https://gorm.io/docs/query.html

  • CRUD ฉบับ GORM
go
package main

import (
  "fmt"
  "gorm.io/gorm"
  "log"
)

type Book struct {
  gorm.Model
  Name        string
  Author      string
  Description string
}

func CreateBook(db *gorm.DB, book *Book) {
  result := db.Create(book)
  if result.Error != nil {
    log.Fatalf("Error creating book: %v", result.Error)
  }
  fmt.Println("Book created successfully")
}

func GetBook(db *gorm.DB, id uint) *Book {
  var book Book
  result := db.First(&book, id)
  if result.Error != nil {
    log.Fatalf("Error finding book: %v", result.Error)
  }
  return &book
}

func UpdateBook(db *gorm.DB, book *Book) {
  result := db.Save(book)
  if result.Error != nil {
    log.Fatalf("Error updating book: %v", result.Error)
  }
  fmt.Println("Book updated successfully")
}

func DeleteBook(db *gorm.DB, id uint) {
  var book Book
  result := db.Delete(&book, id)
  if result.Error != nil {
    log.Fatalf("Error deleting book: %v", result.Error)
  }
  fmt.Println("Book deleted successfully")
}
  • ตัวอย่างการเรียกใช้ที่ main.go
go
func main() {
  // Config Gorm เหมือนเดิม

  // Create a new book
  newBook := Book{Name: "The Go Programming Language", Author: "Alan A. A. Donovan", Description: "Comprehensive guide to Go"}
  CreateBook(db, &newBook)

  // // Get a book
  book := GetBook(db, 1) // Assuming the ID of the book is 1
  // fmt.Println("Book Retrieved:", book)

  // // Update a book
  book.Name = "The Go Programming Language, Updated Edition"
  UpdateBook(db, book)

  // Delete a book
  DeleteBook(db, book.ID)
}

การ Delete ใน GORM

Ref: https://gorm.io/docs/delete.html

  • Default ของ Gorm คือ Soft Delete
  • Soft Delete คือ feature ที่ record ไม่ได้โดนลบไปจริงๆ แต่แค่จะทำการ mark ว่า delete ไว้เฉยๆ
  • ใน GORM default จะทำการสร้าง field ที่ชื่อ DeletedAt ไว้ เมื่อมีการลบจะเป็นการ update วันที่ของ DeletedAt เอาไว้

ตัวอย่างการ Soft Delete crud-01

หากต้องการ Hard Delete

go
func HardDeleteBook(db *gorm.DB, id uint) error {
  var book Book
  result := db.Unscoped().Delete(&book, id)
  if result.Error != nil {
    return result.Error
  }
  fmt.Println("Book hard deleted successfully")
  return nil
}

Search, Sort in GORM

Ref: https://gorm.io/docs/query.html

go
func getBooksSortedByCreatedAt(db *gorm.DB) ([]Book, error) {
  var books []Book
  result := db.Order("created_at desc").Find(&books)
  if result.Error != nil {
    return nil, result.Error
  }
  return books, nil
}

func getBooksByAuthorName(db *gorm.DB, authorName string) ([]Book, error) {
  var books []Book
  result := db.Where("author = ?", authorName).Find(&books)
  if result.Error != nil {
    return nil, result.Error
  }
  return books, nil
}