GORM simplifies database interactions by mapping Go structs to database tables. Understanding how to declare models in GORM is fundamental for leveraging its full capabilities.
Deklarasi Model
Models are defined using normal structs. These structs can contain fields with basic Go types, pointers or aliases of these types, or even custom types, as long as they implement the Scanner and Valuer interfaces from the database/sql
package
Pertimbangkan contoh model User
berikut ini:
type User struct { |
Dalam model ini:
- Tipe data dasar seperti
uint
,string
, danuint8
digunakan secara langsung. - Sebuah pointer ke tipe seperti
*string
dan*time.Time
mengindikasikan bidang yang dapat bernilai null. sql.NullString
dansql.NullTime
dari packagedatabase/sql
digunakan untuk bidang yang dapat bernilai null dengan kontrol yang lebih luas.CreatedAt
danUpdatedAt
adalah bidang khusus yang secara otomatis diisi oleh GORM dengan waktu saat ini ketika record dibuat atau diperbarui.- Non-exported fields (starting with a small letter) are not mapped
Selain fitur dasar deklarasi model di GORM, penting untuk menyoroti dukungan serialisasi melalui tag serializer. Fitur ini meningkatkan fleksibilitas bagaimana data disimpan dan diambil dari database, terutama untuk bidang yang memerlukan logika serialisasi khusus, Lihat Serializer untuk penjelasan yang lebih rinci
Konvensi
Primary Key: GORM menggunakan bidang bernama
ID
sebagai primary key default untuk setiap model.Table Names: By default, GORM converts struct names to
snake_case
and pluralizes them for table names. For instance, aUser
struct becomesusers
in the database.Column Names: GORM automatically converts struct field names to
snake_case
for column names in the database.Timestamp Fields: GORM uses fields named
CreatedAt
andUpdatedAt
to automatically track the creation and update times of records.
Following these conventions can greatly reduce the amount of configuration or code you need to write. However, GORM is also flexible, allowing you to customize these settings if the default conventions don’t fit your requirements. You can learn more about customizing these conventions in GORM’s documentation on conventions.
gorm.Model
GORM provides a predefined struct named gorm.Model
, which includes commonly used fields:
// definisi gorm.Model |
Embedding in Your Struct: You can embed
gorm.Model
directly in your structs to include these fields automatically. This is useful for maintaining consistency across different models and leveraging GORM’s built-in conventions, refer Embedded StructFields Included:
ID
: A unique identifier for each record (primary key).CreatedAt
: Automatically set to the current time when a record is created.UpdatedAt
: Automatically updated to the current time whenever a record is updated.DeletedAt
: Used for soft deletes (marking records as deleted without actually removing them from the database).
Advanced
Field-Level Permission
Exported fields have all permissions when doing CRUD with GORM, and GORM allows you to change the field-level permission with tag, so you can make a field to be read-only, write-only, create-only, update-only or ignored
CATATAN field yang diabaikan tidak akan dibuat saat menggunakan GORM Migrator untuk membuat tabel
type User struct { |
Creating/Updating Time/Unix (Milli/Nano) Seconds Tracking
GORM menggunakan CreatedAt
, UpdatedAt
untuk melacak waktu pembuatan/pembaruan berdasarkan konvensi, dan GORM akan menyetel waktu saat ini saat membuat/memperbarui jika field-nya ditentukan
Untuk menggunakan field dengan nama yang berbeda, Anda dapat mengonfigurasi field tersebut dengan tag autoCreateTime
, autoUpdateTime
Jika Anda lebih suka menyimpan UNIX (mili/nano) detik daripada waktu, Anda cukup mengubah tipe data field dari time.Time
menjadi int
type User struct { |
Embedded Struct
Untuk field anonim, GORM akan memasukkan field-nya ke dalam struct induknya, misalnya:
type Author struct { |
For a normal struct field, you can embed it with the tag embedded
, for example:
type Author struct { |
And you can use tag embeddedPrefix
to add prefix to embedded fields’ db name, for example:
type Blog struct { |
Tags are optional to use when declaring models, GORM supports the following tags: Tags are case insensitive, however camelCase
is preferred. If multiple tags are used they should be separated by a semicolon (;
). Characters that have special meaning to the parser can be escaped with a backslash (\
) allowing them to be used as parameter values.
Nama Tag | Deskripsi |
---|---|
column | column db name |
type | column data type, prefer to use compatible general type, e.g: bool, int, uint, float, string, time, bytes, which works for all databases, and can be used with other tags together, like not null , size , autoIncrement … specified database data type like varbinary(8) also supported, when using specified database data type, it needs to be a full database data type, for example: MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT |
serializer | specifies serializer for how to serialize and deserialize data into db, e.g: serializer:json/gob/unixtime |
size | specifies column data size/length, e.g: size:256 |
primaryKey | specifies column as primary key |
unique | specifies column as unique |
default | specifies column default value |
precision | specifies column precision |
scale | specifies column scale |
not null | specifies column as NOT NULL |
autoIncrement | specifies column auto incrementable |
autoIncrementIncrement | auto increment step, controls the interval between successive column values |
embedded | embed the field |
embeddedPrefix | column name prefix for embedded fields |
autoCreateTime | track current time when creating, for int fields, it will track unix seconds, use value nano /milli to track unix nano/milli seconds, e.g: autoCreateTime:nano |
autoUpdateTime | track current time when creating/updating, for int fields, it will track unix seconds, use value nano /milli to track unix nano/milli seconds, e.g: autoUpdateTime:milli |
index | create index with options, use same name for multiple fields creates composite indexes, refer Indexes for details |
uniqueIndex | same as index , but create uniqued index |
check | creates check constraint, eg: check:age > 13 , refer Constraints |
<- | set field’s write permission, <-:create create-only field, <-:update update-only field, <-:false no write permission, <- create and update permission |
-> | set field’s read permission, ->:false no read permission |
- | ignore this field, - no read/write permission, -:migration no migrate permission, -:all no read/write/migrate permission |
comment | add comment for field when migration |
Associations Tags
GORM allows configure foreign keys, constraints, many2many table through tags for Associations, check out the Associations section for details