Belajar Goravel Framework - Part 4 - Migration, Mo...
Di sesi ini, kita akan membahas bagaimana menghubungkan Goravel dengan database dan mulai bekerja dengan data menggunakan fitur bawaan framework:
- Migration → Membuat struktur tabel di database dengan mudah.
- Model → Representasi tabel sebagai object di dalam kode.
- Seeder → Mengisi data awal ke dalam tabel.
- Factory → Membuat template data dummy untuk testing dan development.
- Faker → Menghasilkan data palsu (fake data) seperti nama, email, teks, dll.
Migration
Goravel menyediakan perintah artisan mirip Laravel:
go run . artisan make:migration create_posts_table
Perintah ini akan membuat file migration di folder database/migrations/. Contoh isi file migration adalah seperti berikut:
package migrations
import (
"github.com/goravel/framework/contracts/database/schema"
"github.com/goravel/framework/facades"
)
type M20250930173224CreatePostsTable struct{}
// Signature The unique signature for the migration.
func (r *M20250930173224CreatePostsTable) Signature() string {
return "20250930173224_create_posts_table"
}
// Up Run the migrations.
func (r *M20250930173224CreatePostsTable) Up() error {
if !facades.Schema().HasTable("posts") {
return facades.Schema().Create("posts", func(table schema.Blueprint) {
table.ID()
table.String("title", 255)
table.Text("body")
table.String("status", 20)
table.TimestampsTz()
table.SoftDeletes()
})
}
return nil
}
// Down Reverse the migrations.
func (r *M20250930173224CreatePostsTable) Down() error {
return facades.Schema().DropIfExists("posts")
}```
Jalankan migration dengan perintah:
```shell
go run . artisan migrate
Jika ingin rollback migration:
go run . artisan migrate:rollback
Bagian dari Series: Seri Tutorial Belajar Framework Goravel Rest API untuk Pemula
Overview Seri ini membahas cara membangun REST API menggunakan Goravel, framework web berbasis Golang yang terinspirasi dari Laravel. Materi mencakup...
Lihat Series Lengkap