Documentation
¶
Index ¶
- Constants
- Variables
- func AddGlobalScope(model string, scope Scope)
- func Attach(db *DB, pivotTable, foreignKey, relatedKey string, parentID, relatedID any) error
- func ClearCache(modelType any)
- func Detach(db *DB, pivotTable, foreignKey, relatedKey string, parentID, relatedID any) error
- func DispatchModelEvent(model any, event string) bool
- func GetModelAttribute(model any, name string) any
- func GetMorphType(name string) reflect.Type
- func GetTableName(model any) string
- func IsPreventLazyLoading() bool
- func Make[T any](db *DB, factory Factory[T], overrides ...map[string]any) (*T, error)
- func MakeMany[T any](db *DB, factory Factory[T], count int, overrides ...map[string]any) ([]*T, error)
- func Observe(model string, observer Observer)
- func RegisterMorph(name string, model any)
- func Seed[T any](db *DB, factory Factory[T], count int) error
- func SetEventManager(m EventDispatcher)
- func SetModelAttribute(model any, name string, value any)
- func SetPreventLazyLoading(prevent bool)
- func Sync(db *DB, pivotTable, foreignKey, relatedKey string, parentID any, ...) error
- func ToArray[T any](model *T) map[string]any
- func Toggle(db *DB, pivotTable, foreignKey, relatedKey string, parentID, relatedID any) error
- func UUID() string
- type AfterCreateHook
- type AfterDeleteHook
- type AfterRestoreHook
- type AfterSaveHook
- type AfterUpdateHook
- type BeforeCreateHook
- type BeforeDeleteHook
- type BeforeRestoreHook
- type BeforeSaveHook
- type BeforeUpdateHook
- type BelongsTo
- type BelongsToMany
- type BoolCast
- type Cast
- type Castable
- type DB
- func (db *DB) Begin(ctx context.Context) (*DB, error)
- func (db *DB) BeginTx() (*DB, error)
- func (db *DB) Commit() error
- func (db *DB) Dialect() (dialect.Dialect, error)
- func (db *DB) InTransaction() bool
- func (db *DB) RawDB() query.QueryExecer
- func (db *DB) Rollback() error
- func (db *DB) Transaction(ctx context.Context, fn func(txDB *DB) error) error
- func (db *DB) TransactionFn(fn func(txDB *DB) error) error
- type DateTimeCast
- type EventDispatcher
- type Factory
- type FieldMeta
- type FloatCast
- type HasMany
- type HasOne
- type IntCast
- type JSONCast
- type MassAssignable
- type Model
- type ModelCreated
- type ModelCreating
- type ModelDeleted
- type ModelDeleting
- type ModelMetadata
- type ModelQuery
- func (q *ModelQuery[T]) Chunk(size int, callback func([]T) error) error
- func (q *ModelQuery[T]) CursorPaginate(perPage int, after any) (*pagination.CursorPaginator[T], error)
- func (q *ModelQuery[T]) Delete(model *T) error
- func (q *ModelQuery[T]) Distinct() *ModelQuery[T]
- func (q *ModelQuery[T]) Find(id any) (*T, error)
- func (q *ModelQuery[T]) FindOrFail(id any) (*T, error)
- func (q *ModelQuery[T]) First() (*T, error)
- func (q *ModelQuery[T]) FirstOrCreate(attributes map[string]any, values ...map[string]any) (*T, bool, error)
- func (q *ModelQuery[T]) FirstOrNew(attributes map[string]any, values ...map[string]any) (*T, bool, error)
- func (q *ModelQuery[T]) ForceDelete(model *T) error
- func (q *ModelQuery[T]) Get() ([]*T, error)
- func (q *ModelQuery[T]) Insert(model *T) error
- func (q *ModelQuery[T]) LockForUpdate() *ModelQuery[T]
- func (q *ModelQuery[T]) OnlyTrashed() *ModelQuery[T]
- func (q *ModelQuery[T]) Paginate(perPage, page int) (*pagination.LengthAwarePaginator[T], error)
- func (q *ModelQuery[T]) Restore(model *T) error
- func (q *ModelQuery[T]) Save(model *T) error
- func (q *ModelQuery[T]) SharedLock() *ModelQuery[T]
- func (q *ModelQuery[T]) SimplePaginate(perPage, page int) (*pagination.SimplePaginator[T], error)
- func (q *ModelQuery[T]) ToJSON(model *T) (string, error)
- func (q *ModelQuery[T]) Update(model *T) error
- func (q *ModelQuery[T]) Where(column, operator string, value any) *ModelQuery[T]
- func (q *ModelQuery[T]) WhereDoesntHave(relation string) *ModelQuery[T]
- func (q *ModelQuery[T]) WhereHas(relation string, callback func(b *query.Builder) *query.Builder) *ModelQuery[T]
- func (q *ModelQuery[T]) WhereRelation(relation, column, operator string, value any) *ModelQuery[T]
- func (q *ModelQuery[T]) With(relation string) *ModelQuery[T]
- func (q *ModelQuery[T]) WithTrashed() *ModelQuery[T]
- type ModelRestored
- type ModelRestoring
- type ModelSaved
- type ModelSaving
- type ModelUpdated
- type ModelUpdating
- type MorphMany
- type MorphOne
- type MorphTo
- type Observer
- type Scope
- type ScopeFunc
- type SerializesAttributes
- type StringCast
- type Touches
- type UUIDModel
- type UUIDTrait
Constants ¶
const ( CastDatetime = "datetime" CastJSON = "json" CastBool = "bool" CastInt = "int" CastFloat = "float" CastString = "string" )
Built-in cast types (Laravel-like)
Variables ¶
var ( PreventLazyLoading bool HasUuids bool )
ModelConfig holds strictness rules.
var ErrCancelled = errors.New("operation cancelled by model observer")
Functions ¶
func AddGlobalScope ¶
AddGlobalScope registers a global scope for a given model type name.
func ClearCache ¶
func ClearCache(modelType any)
ClearCache removes cached metadata for the given model type. Call this after altering struct tags or table mappings at runtime.
func DispatchModelEvent ¶
DispatchModelEvent fires registered observers, interface hooks, and global events. Returning false from a "ing" event (like Creating) halts the operation.
func GetModelAttribute ¶
GetModelAttribute retrieves the value of an attribute on a model. It first looks for a method Get<Name>Attribute() (e.g. GetTitleAttribute). Falls back to direct struct field access (case-insensitive). This enables Laravel-style accessors without magic.
func GetMorphType ¶
GetMorphType returns the registered reflect.Type for a morph name, or nil.
func GetTableName ¶
GetTableName resolves the table name for a model instance using metadata.
func IsPreventLazyLoading ¶
func IsPreventLazyLoading() bool
IsPreventLazyLoading returns whether lazy loading prevention is enabled.
func MakeMany ¶
func MakeMany[T any](db *DB, factory Factory[T], count int, overrides ...map[string]any) ([]*T, error)
MakeMany creates multiple model instances.
func RegisterMorph ¶
RegisterMorph registers a name (used in *_type columns) to a model struct type. Call this in init() or bootstrap for each polymorphic model.
func SetEventManager ¶
func SetEventManager(m EventDispatcher)
SetEventManager injects the global event manager.
func SetModelAttribute ¶
SetModelAttribute sets an attribute value on a model. Looks for Set<Name>Attribute(value) method first (mutator). Falls back to setting the struct field directly if exported.
func SetPreventLazyLoading ¶
func SetPreventLazyLoading(prevent bool)
SetPreventLazyLoading enables/disables lazy loading prevention.
Types ¶
type AfterCreateHook ¶
type AfterCreateHook interface {
AfterCreate() error
}
type AfterDeleteHook ¶
type AfterDeleteHook interface {
AfterDelete() error
}
type AfterRestoreHook ¶
type AfterRestoreHook interface {
AfterRestore() error
}
type AfterSaveHook ¶
type AfterSaveHook interface {
AfterSave() error
}
type AfterUpdateHook ¶
type AfterUpdateHook interface {
AfterUpdate() error
}
type BeforeCreateHook ¶
type BeforeCreateHook interface {
BeforeCreate() error
}
type BeforeDeleteHook ¶
type BeforeDeleteHook interface {
BeforeDelete() error
}
type BeforeRestoreHook ¶
type BeforeRestoreHook interface {
BeforeRestore() error
}
type BeforeSaveHook ¶
type BeforeSaveHook interface {
BeforeSave() error
}
type BeforeUpdateHook ¶
type BeforeUpdateHook interface {
BeforeUpdate() error
}
type BelongsTo ¶
type BelongsTo[T any] struct { Model *T }
BelongsTo represents an inverse one-to-many relationship.
type BelongsToMany ¶
type BelongsToMany[T any] struct { Models []T }
BelongsToMany represents a many-to-many relationship via a pivot table.
type DB ¶
type DB struct {
Conn query.QueryExecer
Builder *query.Builder
// contains filtered or unexported fields
}
DB represents the ORM database connection.
func (*DB) Begin ¶
Begin starts a new database transaction and returns a new *DB instance that operates within that transaction.
func (*DB) Commit ¶
Commit commits the current transaction. It only works if this DB instance was created via Begin() or Transaction().
func (*DB) InTransaction ¶
InTransaction returns true if this DB instance is operating inside a transaction.
func (*DB) RawDB ¶
func (db *DB) RawDB() query.QueryExecer
RawDB returns the underlying query executor (usually *sql.DB or *sql.Tx).
func (*DB) Transaction ¶
Transaction executes a function within a database transaction.
type DateTimeCast ¶
type DateTimeCast struct{}
type EventDispatcher ¶
type EventDispatcher interface {
Dispatch(event any)
}
EventDispatcher interface allows ORM to dispatch global events without strong coupling to the events package.
type FieldMeta ¶
type FieldMeta struct {
Name string // struct field name
Column string // db tag value
Index int // reflect field index for fast access
IsPrimary bool
IsAuto bool // auto-increment
}
FieldMeta represents cached metadata for a struct field.
type HasMany ¶
type HasMany[T any] struct { // Represents the related models Models []T }
HasMany represents a one-to-many relationship.
type MassAssignable ¶
type MassAssignable interface {
// Fillable returns the list of fields that are allowed to be mass assigned.
// If empty, all fields are allowed unless Guarded is specified.
Fillable() []string
// Guarded returns the list of fields that are not allowed to be mass assigned.
// Use ["*"] to guard all fields by default.
Guarded() []string
}
MassAssignable allows models to control mass assignment protection, similar to Laravel's $fillable and $guarded properties.
type Model ¶
type Model interface {
TableName() string
}
Model represents a generic interface for all Goquent models.
type ModelCreated ¶
type ModelCreated struct{ Model any }
type ModelCreating ¶
type ModelCreating struct{ Model any }
type ModelDeleted ¶
type ModelDeleted struct{ Model any }
type ModelDeleting ¶
type ModelDeleting struct{ Model any }
type ModelMetadata ¶
type ModelMetadata struct {
TableName string
PrimaryKey string
SoftDeleteCol string // empty string if no soft delete field
Fields []FieldMeta
}
ModelMetadata holds cached reflection data for an ORM model.
type ModelQuery ¶
type ModelQuery[T any] struct { // contains filtered or unexported fields }
ModelQuery is an ORM-wrapper around the Query Builder.
func NewQuery ¶
func NewQuery[T any](db *DB) *ModelQuery[T]
func (*ModelQuery[T]) Chunk ¶
func (q *ModelQuery[T]) Chunk(size int, callback func([]T) error) error
Chunk processes results in batches of the given size, calling the callback for each batch. Stops if callback returns error. Excellent for large data processing (Laravel equivalent).
func (*ModelQuery[T]) CursorPaginate ¶
func (q *ModelQuery[T]) CursorPaginate(perPage int, after any) (*pagination.CursorPaginator[T], error)
CursorPaginate is a basic cursor-based paginator (keyset pagination).
func (*ModelQuery[T]) Delete ¶
func (q *ModelQuery[T]) Delete(model *T) error
Delete deletes the given model (or rows matching the query if model is nil).
func (*ModelQuery[T]) Distinct ¶
func (q *ModelQuery[T]) Distinct() *ModelQuery[T]
Distinct adds a DISTINCT clause to the query.
func (*ModelQuery[T]) Find ¶
func (q *ModelQuery[T]) Find(id any) (*T, error)
Find fetches a model by its primary key.
func (*ModelQuery[T]) FindOrFail ¶
func (q *ModelQuery[T]) FindOrFail(id any) (*T, error)
FindOrFail fetches a model by its primary key or returns an error if not found.
func (*ModelQuery[T]) First ¶
func (q *ModelQuery[T]) First() (*T, error)
First fetches the first matching record.
func (*ModelQuery[T]) FirstOrCreate ¶
func (q *ModelQuery[T]) FirstOrCreate(attributes map[string]any, values ...map[string]any) (*T, bool, error)
FirstOrCreate returns the first record matching the attributes, or creates it if not found.
func (*ModelQuery[T]) FirstOrNew ¶
func (q *ModelQuery[T]) FirstOrNew(attributes map[string]any, values ...map[string]any) (*T, bool, error)
FirstOrNew returns the first record matching the attributes, or creates a new instance (not saved).
func (*ModelQuery[T]) ForceDelete ¶
func (q *ModelQuery[T]) ForceDelete(model *T) error
ForceDelete permanently deletes the model.
func (*ModelQuery[T]) Get ¶
func (q *ModelQuery[T]) Get() ([]*T, error)
Get fetches all matching records.
func (*ModelQuery[T]) Insert ¶
func (q *ModelQuery[T]) Insert(model *T) error
Insert creates a new record from the model struct.
func (*ModelQuery[T]) LockForUpdate ¶
func (q *ModelQuery[T]) LockForUpdate() *ModelQuery[T]
LockForUpdate enables pessimistic lock on the query (FOR UPDATE).
func (*ModelQuery[T]) OnlyTrashed ¶
func (q *ModelQuery[T]) OnlyTrashed() *ModelQuery[T]
OnlyTrashed limits the query to only soft-deleted records.
func (*ModelQuery[T]) Paginate ¶
func (q *ModelQuery[T]) Paginate(perPage, page int) (*pagination.LengthAwarePaginator[T], error)
Paginate returns a length-aware paginator (with total count).
func (*ModelQuery[T]) Restore ¶
func (q *ModelQuery[T]) Restore(model *T) error
Restore restores a soft-deleted model.
func (*ModelQuery[T]) Save ¶
func (q *ModelQuery[T]) Save(model *T) error
Save inserts a new model or updates an existing one based on primary key presence.
func (*ModelQuery[T]) SharedLock ¶
func (q *ModelQuery[T]) SharedLock() *ModelQuery[T]
SharedLock enables shared lock (FOR SHARE).
func (*ModelQuery[T]) SimplePaginate ¶
func (q *ModelQuery[T]) SimplePaginate(perPage, page int) (*pagination.SimplePaginator[T], error)
SimplePaginate returns a simple paginator (no total count).
func (*ModelQuery[T]) ToJSON ¶
func (q *ModelQuery[T]) ToJSON(model *T) (string, error)
ToJSON serializes the model to a JSON string.
func (*ModelQuery[T]) Update ¶
func (q *ModelQuery[T]) Update(model *T) error
Update updates an existing model.
func (*ModelQuery[T]) Where ¶
func (q *ModelQuery[T]) Where(column, operator string, value any) *ModelQuery[T]
Where adds a where clause.
func (*ModelQuery[T]) WhereDoesntHave ¶
func (q *ModelQuery[T]) WhereDoesntHave(relation string) *ModelQuery[T]
WhereDoesntHave adds a condition that the relationship has NO related records.
func (*ModelQuery[T]) WhereHas ¶
func (q *ModelQuery[T]) WhereHas(relation string, callback func(b *query.Builder) *query.Builder) *ModelQuery[T]
WhereHas adds a condition that the relationship has related records.
func (*ModelQuery[T]) WhereRelation ¶
func (q *ModelQuery[T]) WhereRelation(relation, column, operator string, value any) *ModelQuery[T]
WhereRelation adds a condition on a related model's column.
func (*ModelQuery[T]) With ¶
func (q *ModelQuery[T]) With(relation string) *ModelQuery[T]
With adds a relationship to be eager-loaded.
func (*ModelQuery[T]) WithTrashed ¶
func (q *ModelQuery[T]) WithTrashed() *ModelQuery[T]
WithTrashed includes soft-deleted records in the query.
type ModelRestored ¶
type ModelRestored struct{ Model any }
type ModelRestoring ¶
type ModelRestoring struct{ Model any }
type ModelSaved ¶
type ModelSaved struct{ Model any }
type ModelSaving ¶
type ModelSaving struct{ Model any }
type ModelUpdated ¶
type ModelUpdated struct{ Model any }
type ModelUpdating ¶
type ModelUpdating struct{ Model any }
type MorphTo ¶
type MorphTo struct {
Model any
}
MorphTo holds dynamically resolved related model for inverse polymorphic relation.
type Observer ¶
type Observer interface {
Creating(model any) bool
Created(model any)
Updating(model any) bool
Updated(model any)
Deleting(model any) bool
Deleted(model any)
}
Observer represents model event hooks.
type SerializesAttributes ¶
type SerializesAttributes interface {
Hidden() []string // fields to hide in serialization
Appends() []string // virtual attributes to always include (must have getters)
}
SerializesAttributes optional interface for controlling JSON/API output.
type StringCast ¶
type StringCast struct{}
type Touches ¶
type Touches interface {
Touches() []string // relation names (e.g. ["post", "author"])
}
Touches allows a model to declare relations that should have their timestamps updated when this model is saved/updated.
type UUIDModel ¶
type UUIDModel struct {
ID string `json:"id" db:"id" gow:"uuid"`
}
UUIDModel is a base struct implementing UUIDTrait.
func (*UUIDModel) GenerateUUID ¶
GenerateUUID generates a new UUID v4.