Documentation
¶
Overview ¶
Package orm is a Lucid-style model layer: a generic repository over GORM models.
Relations, hooks (BeforeCreate, ...) and soft deletes use GORM's native struct tags, interfaces and gorm.DeletedAt; Query.Preload exposes eager loading.
Index ¶
- func Bind[T any](db *migro.DB, v *T) *T
- func CompareHash(hash, plain string) bool
- func EnforceMorphMap(m map[string]any)
- func Fresh[T any](ctx context.Context, v *T) (*T, error)
- func Is(a, b any) bool
- func IsNot(a, b any) bool
- func JSON(v any) ([]byte, error)
- func JSONWith(v any, opts ...SerializeOpt) ([]byte, error)
- func Load[T any](ctx context.Context, db *migro.DB, v *T, relations ...string) error
- func LoadAvg[T any](ctx context.Context, db *migro.DB, v *T, relation, column string) error
- func LoadCount[T any](ctx context.Context, db *migro.DB, v *T, relations ...string) error
- func LoadExists[T any](ctx context.Context, db *migro.DB, v *T, relation string) error
- func LoadMax[T any](ctx context.Context, db *migro.DB, v *T, relation, column string) error
- func LoadMin[T any](ctx context.Context, db *migro.DB, v *T, relation, column string) error
- func LoadSum[T any](ctx context.Context, db *migro.DB, v *T, relation, column string) error
- func MapTo[T, R any](c Collection[T], fn func(m *T) R) []R
- func MorphMap(m map[string]any)
- func NewULID() string
- func NewUUID() string
- func Pluck[T, V any](ctx context.Context, q *Query[T], col string) ([]V, error)
- func PluckAs[T, V any](c Collection[T], col string) ([]V, error)
- func PruneAll(ctx context.Context, db *migro.DB) (map[string]int64, error)
- func Push[T any](ctx context.Context, v *T) error
- func Reduce[T, A any](c Collection[T], initial A, fn func(acc A, m *T) A) A
- func RegisterMorph[T any](r *MorphRegistry, db *migro.DB, alias string) error
- func RegisterPrunable[T any](name string)
- func Replicate[T any](ctx context.Context, v *T, except ...string) (*T, error)
- func ToMap(v any) (map[string]any, error)
- func ToMapWith(v any, opts ...SerializeOpt) (map[string]any, error)
- func Value[T, V any](ctx context.Context, q *Query[T], col string) (V, error)
- type Appends
- type BaseModel
- type BelongsTo
- type BelongsToMany
- func (r *BelongsToMany[T]) Attach(ctx context.Context, ids ...any) error
- func (r *BelongsToMany[T]) AttachWith(ctx context.Context, attrs map[string]any, ids ...any) error
- func (r *BelongsToMany[T]) Detach(ctx context.Context, ids ...any) error
- func (m *BelongsToMany) Get(ctx context.Context) (Collection[T], error)
- func (m *BelongsToMany) Items() Collection[T]
- func (m *BelongsToMany) Query() (*Query[T], error)
- func (r *BelongsToMany[T]) Sync(ctx context.Context, ids ...any) (SyncResult, error)
- func (r *BelongsToMany[T]) SyncWithoutDetaching(ctx context.Context, ids ...any) (SyncResult, error)
- func (r *BelongsToMany[T]) Toggle(ctx context.Context, ids ...any) (SyncResult, error)
- func (r *BelongsToMany[T]) UpdateExistingPivot(ctx context.Context, id any, attrs map[string]any) error
- func (m *BelongsToMany) Value() (driver.Value, error)
- type Cast
- type CastFunc
- type Casted
- type Collection
- func (c Collection[T]) Contains(id any) (bool, error)
- func (c Collection[T]) Count() int
- func (c Collection[T]) Each(fn func(i int, m *T) error) error
- func (c Collection[T]) Except(ids ...any) (Collection[T], error)
- func (c Collection[T]) Filter(keep func(m *T) bool) Collection[T]
- func (c Collection[T]) Find(id any) (*T, error)
- func (c Collection[T]) First() *T
- func (c Collection[T]) Fresh(ctx context.Context) (Collection[T], error)
- func (c Collection[T]) GroupBy(col string) (map[any]Collection[T], error)
- func (c Collection[T]) IsEmpty() bool
- func (c Collection[T]) JSON(opts ...SerializeOpt) ([]byte, error)
- func (c Collection[T]) KeyBy(col string) (map[any]T, error)
- func (c Collection[T]) Last() *T
- func (c Collection[T]) Load(ctx context.Context, relations ...string) error
- func (c Collection[T]) LoadMissing(ctx context.Context, relations ...string) error
- func (c Collection[T]) ModelKeys() ([]any, error)
- func (c Collection[T]) Only(ids ...any) (Collection[T], error)
- func (c Collection[T]) Pluck(col string) ([]any, error)
- func (c Collection[T]) Reject(drop func(m *T) bool) Collection[T]
- func (c Collection[T]) ToMaps(opts ...SerializeOpt) ([]map[string]any, error)
- func (c Collection[T]) Unique(col string) (Collection[T], error)
- type ColumnInfo
- type Connected
- type CursorPage
- type Defaults
- type Fillable
- type GlobalScoped
- type Guarded
- type HasMany
- func (r *HasMany[T]) Create(ctx context.Context, attrs map[string]any) (*T, error)
- func (r *HasMany[T]) CreateMany(ctx context.Context, rows []map[string]any) ([]T, error)
- func (m *HasMany) Get(ctx context.Context) (Collection[T], error)
- func (m *HasMany) Items() Collection[T]
- func (m *HasMany) Query() (*Query[T], error)
- func (r *HasMany[T]) Save(ctx context.Context, child *T) error
- func (r *HasMany[T]) SaveMany(ctx context.Context, children []T) error
- func (m *HasMany) Value() (driver.Value, error)
- type HasManyThrough
- type HasManyThroughLoader
- type HasOne
- func (r *HasOne[T]) Create(ctx context.Context, attrs map[string]any) (*T, error)
- func (o *HasOne) Get(ctx context.Context) (*T, error)
- func (o *HasOne) Item() *T
- func (o *HasOne) Query() (*Query[T], error)
- func (r *HasOne[T]) Save(ctx context.Context, child *T) error
- func (o *HasOne) Value() (driver.Value, error)
- type HasOneThrough
- type Hidden
- type JSONColumn
- func (JSONColumn[T]) GormDBDataType(db *gorm.DB, _ *schema.Field) string
- func (JSONColumn[T]) GormDataType() string
- func (j JSONColumn[T]) MarshalJSON() ([]byte, error)
- func (j *JSONColumn[T]) Scan(src any) error
- func (j *JSONColumn[T]) UnmarshalJSON(b []byte) error
- func (j JSONColumn[T]) Value() (driver.Value, error)
- type MassPrunable
- type Model
- func (m *Model[T]) All(ctx context.Context) (Collection[T], error)
- func (m *Model[T]) Create(ctx context.Context, v *T) error
- func (m *Model[T]) CreateFrom(ctx context.Context, attrs map[string]any) (*T, error)
- func (m *Model[T]) CreateMany(ctx context.Context, vs []T) error
- func (m *Model[T]) Delete(ctx context.Context, v *T) error
- func (m *Model[T]) Destroy(ctx context.Context, ids ...any) (int64, error)
- func (m *Model[T]) Find(ctx context.Context, id any) (*T, error)
- func (m *Model[T]) FindBy(ctx context.Context, column string, value any) (*T, error)
- func (m *Model[T]) FindMany(ctx context.Context, ids ...any) (Collection[T], error)
- func (m *Model[T]) FindOrFail(ctx context.Context, id any) (*T, error)
- func (m *Model[T]) FirstOrCreate(ctx context.Context, where T, attrs T) (*T, bool, error)
- func (m *Model[T]) FirstOrCreateMany(ctx context.Context, keys []string, rows []T) ([]T, error)
- func (m *Model[T]) FirstOrNew(ctx context.Context, where T, attrs T) (*T, bool, error)
- func (m *Model[T]) InsertOrIgnore(ctx context.Context, rows []T) error
- func (m *Model[T]) Make(attrs map[string]any) (*T, error)
- func (m *Model[T]) Prune(ctx context.Context) (int64, error)
- func (m *Model[T]) Query() *Query[T]
- func (m *Model[T]) Save(ctx context.Context, v *T) error
- func (m *Model[T]) Truncate(ctx context.Context) error
- func (m *Model[T]) UpdateOrCreate(ctx context.Context, where T, values T) (*T, error)
- func (m *Model[T]) UpdateOrCreateMany(ctx context.Context, keys []string, rows []T) ([]T, error)
- func (m *Model[T]) Upsert(ctx context.Context, rows []T, uniqueBy []string, update []string) error
- type ModelInfo
- type MorphMany
- func (r *MorphMany[T]) Create(ctx context.Context, attrs map[string]any) (*T, error)
- func (r *MorphMany[T]) CreateMany(ctx context.Context, rows []map[string]any) ([]T, error)
- func (m *MorphMany) Get(ctx context.Context) (Collection[T], error)
- func (m *MorphMany) Items() Collection[T]
- func (m *MorphMany) Query() (*Query[T], error)
- func (r *MorphMany[T]) Save(ctx context.Context, child *T) error
- func (r *MorphMany[T]) SaveMany(ctx context.Context, children []T) error
- func (m *MorphMany) Value() (driver.Value, error)
- type MorphOne
- func (r *MorphOne[T]) Create(ctx context.Context, attrs map[string]any) (*T, error)
- func (o *MorphOne) Get(ctx context.Context) (*T, error)
- func (o *MorphOne) Item() *T
- func (o *MorphOne) Query() (*Query[T], error)
- func (r *MorphOne[T]) Save(ctx context.Context, child *T) error
- func (o *MorphOne) Value() (driver.Value, error)
- type MorphRegistry
- type MorphTo
- type MorphToMany
- func (r *MorphToMany[T]) Attach(ctx context.Context, ids ...any) error
- func (r *MorphToMany[T]) AttachWith(ctx context.Context, attrs map[string]any, ids ...any) error
- func (r *MorphToMany[T]) Detach(ctx context.Context, ids ...any) error
- func (m *MorphToMany) Get(ctx context.Context) (Collection[T], error)
- func (m *MorphToMany) Items() Collection[T]
- func (m *MorphToMany) Query() (*Query[T], error)
- func (r *MorphToMany[T]) Sync(ctx context.Context, ids ...any) (SyncResult, error)
- func (r *MorphToMany[T]) SyncWithoutDetaching(ctx context.Context, ids ...any) (SyncResult, error)
- func (r *MorphToMany[T]) Toggle(ctx context.Context, ids ...any) (SyncResult, error)
- func (m *MorphToMany) Value() (driver.Value, error)
- type MorphToManyLoader
- func (r MorphToManyLoader[T]) Attach(ctx context.Context, db *migro.DB, parentKey any, relatedKeys ...any) error
- func (r MorphToManyLoader[T]) Detach(ctx context.Context, db *migro.DB, parentKey any, relatedKeys ...any) error
- func (r MorphToManyLoader[T]) Load(ctx context.Context, db *migro.DB, parentKeys []any) (map[any][]T, error)
- func (r MorphToManyLoader[T]) Sync(ctx context.Context, db *migro.DB, parentKey any, relatedKeys ...any) error
- type MorphedByMany
- func (r *MorphedByMany[T]) Attach(ctx context.Context, ids ...any) error
- func (r *MorphedByMany[T]) Detach(ctx context.Context, ids ...any) error
- func (m *MorphedByMany) Get(ctx context.Context) (Collection[T], error)
- func (m *MorphedByMany) Items() Collection[T]
- func (m *MorphedByMany) Query() (*Query[T], error)
- func (r *MorphedByMany[T]) Sync(ctx context.Context, ids ...any) (SyncResult, error)
- func (m *MorphedByMany) Value() (driver.Value, error)
- type MorphedByManyLoader
- type NamedScope
- type Page
- type Pivot
- type PivotModels
- type Prunable
- type Pruning
- type Query
- func (q *Query[T]) Apply(scopes ...func(*Query[T]) *Query[T]) *Query[T]
- func (q *Query[T]) Avg(ctx context.Context, col string) (float64, error)
- func (q *Query[T]) Chunk(ctx context.Context, size int, fn func(rows []T) error) error
- func (q *Query[T]) ChunkByID(ctx context.Context, size int, column string, fn func(rows []T) error) error
- func (q *Query[T]) Count(ctx context.Context) (int64, error)
- func (q *Query[T]) Cursor(ctx context.Context) iter.Seq2[*T, error]
- func (q *Query[T]) CursorPaginate(ctx context.Context, perPage int, cursor string) (CursorPage[T], error)
- func (q *Query[T]) DB() *migro.DB
- func (q *Query[T]) Decrement(ctx context.Context, col string, n int) (int64, error)
- func (q *Query[T]) Delete(ctx context.Context) (int64, error)
- func (q *Query[T]) Distinct(cols ...string) *Query[T]
- func (q *Query[T]) DoesntHave(relation string) *Query[T]
- func (q *Query[T]) Each(ctx context.Context, size int, fn func(*T) error) error
- func (q *Query[T]) Exists(ctx context.Context) (bool, error)
- func (q *Query[T]) First(ctx context.Context) (*T, error)
- func (q *Query[T]) FirstOrFail(ctx context.Context) (*T, error)
- func (q *Query[T]) FirstWhere(ctx context.Context, col string, value any) (*T, error)
- func (q *Query[T]) Get(ctx context.Context) (Collection[T], error)
- func (q *Query[T]) GroupBy(cols ...string) *Query[T]
- func (q *Query[T]) Has(relation string) *Query[T]
- func (q *Query[T]) Having(query any, args ...any) *Query[T]
- func (q *Query[T]) Increment(ctx context.Context, col string, n int) (int64, error)
- func (q *Query[T]) Joins(clause string, args ...any) *Query[T]
- func (q *Query[T]) Latest(col ...string) *Query[T]
- func (q *Query[T]) Lazy(ctx context.Context, size int) iter.Seq2[*T, error]
- func (q *Query[T]) Limit(n int) *Query[T]
- func (q *Query[T]) LockForUpdate() *Query[T]
- func (q *Query[T]) Max(ctx context.Context, col string) (any, error)
- func (q *Query[T]) Min(ctx context.Context, col string) (any, error)
- func (q *Query[T]) Not(query any, args ...any) *Query[T]
- func (q *Query[T]) Offset(n int) *Query[T]
- func (q *Query[T]) Oldest(col ...string) *Query[T]
- func (q *Query[T]) OnlyTrashed() *Query[T]
- func (q *Query[T]) OrWhere(query any, args ...any) *Query[T]
- func (q *Query[T]) OrWhereRaw(sql string, args ...any) *Query[T]
- func (q *Query[T]) OrderBy(col, dir string) *Query[T]
- func (q *Query[T]) OrderByDesc(col string) *Query[T]
- func (q *Query[T]) Paginate(ctx context.Context, page, perPage int) (Page[T], error)
- func (q *Query[T]) Preload(relation string, args ...any) *Query[T]
- func (q *Query[T]) Scope(fns ...func(*gorm.DB) *gorm.DB) *Query[T]
- func (q *Query[T]) Select(cols ...string) *Query[T]
- func (q *Query[T]) SharedLock() *Query[T]
- func (q *Query[T]) SimplePaginate(ctx context.Context, page, perPage int) (SimplePage[T], error)
- func (q *Query[T]) Sole(ctx context.Context) (*T, error)
- func (q *Query[T]) Sum(ctx context.Context, col string) (float64, error)
- func (q *Query[T]) Tap(fn func(*Query[T])) *Query[T]
- func (q *Query[T]) ToSQL(ctx context.Context) (string, error)
- func (q *Query[T]) Union(others ...*Query[T]) *Query[T]
- func (q *Query[T]) UnionAll(others ...*Query[T]) *Query[T]
- func (q *Query[T]) Update(ctx context.Context, values map[string]any) (int64, error)
- func (q *Query[T]) When(cond bool, fn func(*Query[T]) *Query[T]) *Query[T]
- func (q *Query[T]) Where(query any, args ...any) *Query[T]
- func (q *Query[T]) WhereBelongsTo(parent any, relation ...string) *Query[T]
- func (q *Query[T]) WhereBetween(col string, from, to any) *Query[T]
- func (q *Query[T]) WhereColumn(left, op, right string) *Query[T]
- func (q *Query[T]) WhereDate(col, op string, value any) *Query[T]
- func (q *Query[T]) WhereDay(col, op string, value int) *Query[T]
- func (q *Query[T]) WhereDoesntHave(relation string, scope scopeFn) *Query[T]
- func (q *Query[T]) WhereExists(sub SubQuery) *Query[T]
- func (q *Query[T]) WhereFullText(search string, cols ...string) *Query[T]
- func (q *Query[T]) WhereFullTextBoolean(search string, cols ...string) *Query[T]
- func (q *Query[T]) WhereHas(relation string, scope scopeFn) *Query[T]
- func (q *Query[T]) WhereHasMorph(relation string, aliases []string, scope scopeFn) *Query[T]
- func (q *Query[T]) WhereIn(col string, values any) *Query[T]
- func (q *Query[T]) WhereJSON(col, path, op string, value any) *Query[T]
- func (q *Query[T]) WhereLike(col, pattern string) *Query[T]
- func (q *Query[T]) WhereMonth(col, op string, value int) *Query[T]
- func (q *Query[T]) WhereNotExists(sub SubQuery) *Query[T]
- func (q *Query[T]) WhereNotIn(col string, values any) *Query[T]
- func (q *Query[T]) WhereNotLike(col, pattern string) *Query[T]
- func (q *Query[T]) WhereNotNull(col string) *Query[T]
- func (q *Query[T]) WhereNull(col string) *Query[T]
- func (q *Query[T]) WhereRaw(sql string, args ...any) *Query[T]
- func (q *Query[T]) WhereRelation(relation string, query any, args ...any) *Query[T]
- func (q *Query[T]) WhereYear(col, op string, value int) *Query[T]
- func (q *Query[T]) With(relation string, scope ...scopeFn) *Query[T]
- func (q *Query[T]) WithAvg(relation, column string) *Query[T]
- func (q *Query[T]) WithCount(relations ...string) *Query[T]
- func (q *Query[T]) WithExists(relation string) *Query[T]
- func (q *Query[T]) WithMax(relation, column string) *Query[T]
- func (q *Query[T]) WithMin(relation, column string) *Query[T]
- func (q *Query[T]) WithSum(relation, column string) *Query[T]
- func (q *Query[T]) WithTrashed() *Query[T]
- func (q *Query[T]) WithoutGlobalScope(names ...string) *Query[T]
- func (q *Query[T]) WithoutGlobalScopes() *Query[T]
- type R
- func (r *R) Fail(err error)
- func (r *R) Loaded(relation string) bool
- func (r *R) Merge(fields map[string]any)
- func (r *R) MergeWhen(cond bool, fields map[string]any)
- func (r *R) Set(key string, v any)
- func (r *R) When(cond bool, key string, v any)
- func (r *R) WhenLoaded(relation string, fn func() (any, error))
- type Record
- func (b *Record) Decrement(ctx context.Context, column string, n int) error
- func (b *Record) Delete(ctx context.Context) error
- func (b *Record) DeleteQuietly(ctx context.Context) error
- func (b *Record) Dirty() map[string]any
- func (b *Record) Exists() bool
- func (b *Record) Extra(key string) any
- func (b *Record) Extras() map[string]any
- func (b *Record) Fill(attrs map[string]any) error
- func (b *Record) ForceDelete(ctx context.Context) error
- func (b *Record) GetAttribute(column string) (any, error)
- func (b *Record) GetChanges() map[string]any
- func (b *Record) GetOriginal(column string) any
- func (b *Record) Increment(ctx context.Context, column string, n int) error
- func (b *Record) IncrementEach(ctx context.Context, amounts map[string]int) error
- func (b *Record) IsClean(columns ...string) bool
- func (b *Record) IsDirty(columns ...string) bool
- func (b *Record) Refresh(ctx context.Context) error
- func (b *Record) Restore(ctx context.Context) error
- func (b *Record) Save(ctx context.Context) error
- func (b *Record) SaveQuietly(ctx context.Context) error
- func (b *Record) SaveWithoutTimestamps(ctx context.Context) error
- func (b *Record) SetAttribute(column string, v any) error
- func (b *Record) Touch(ctx context.Context) error
- func (b *Record) Trashed() bool
- func (b *Record) Update(ctx context.Context, attrs map[string]any) error
- func (b *Record) UseTransaction(tx *migro.DB)
- func (b *Record) WasChanged(columns ...string) bool
- func (b *Record) WasRecentlyCreated() bool
- type Ref
- type RelationInfo
- type Resource
- func (r *Resource[T]) Additional(extra map[string]any) *Resource[T]
- func (r *Resource[T]) Collection(items []T) (any, error)
- func (r *Resource[T]) List(items []T) ([]map[string]any, error)
- func (r *Resource[T]) Make(m *T) (any, error)
- func (r *Resource[T]) Map(m *T) (map[string]any, error)
- func (r *Resource[T]) Paginated(page Page[T], baseURL ...string) (any, error)
- func (r *Resource[T]) WithoutWrapping() *Resource[T]
- func (r *Resource[T]) Wrap(key string) *Resource[T]
- type SerializeAs
- type SerializeOpt
- type SimplePage
- type SoftDeleteModel
- type SoftDeleteULIDModel
- type SoftDeleteUUIDModel
- type SubQuery
- type SyncResult
- type Touches
- type ULIDKey
- type ULIDModel
- type UUIDKey
- type UUIDModel
- type Visible
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Bind ¶
Bind attaches v (a struct pointer) to db so its instance methods and relations work. A model with a non-zero primary key is treated as already persisted.
func CompareHash ¶
CompareHash reports whether plain matches a bcrypt hash made by CastHashed.
func EnforceMorphMap ¶
EnforceMorphMap is MorphMap that also refuses models missing from the map (Laravel's Relation::enforceMorphMap): without it an unmapped model silently stores its type name, and renaming the Go type later orphans every row.
func Is ¶
Is reports whether a and b are the same row: the same model type and the same non-zero primary key (Eloquent's is). IsNot is its negation.
func JSONWith ¶
func JSONWith(v any, opts ...SerializeOpt) ([]byte, error)
JSONWith is JSON with per-call options.
func LoadCount ¶
LoadCount, LoadSum, LoadAvg, LoadMin, LoadMax and LoadExists compute the same aggregates for models already fetched (Eloquent's loadCount, loadSum, ...).
func LoadExists ¶
func MapTo ¶
func MapTo[T, R any](c Collection[T], fn func(m *T) R) []R
MapTo transforms every model into another type. It is a function because Go methods cannot introduce a type parameter.
func MorphMap ¶
MorphMap registers the aliases stored in *_type columns (Laravel's Relation::morphMap):
orm.MorphMap(map[string]any{"post": Post{}, "video": Video{}})
Models missing from the map use their snake_case type name as alias.
func NewULID ¶
func NewULID() string
NewULID returns a ULID: 48 bits of millisecond time and 80 random bits in Crockford base32.
func NewUUID ¶
func NewUUID() string
NewUUID returns a UUIDv7: a millisecond timestamp followed by random bits, so ids sort by creation.
func PluckAs ¶
func PluckAs[T, V any](c Collection[T], col string) ([]V, error)
PluckAs is Pluck with the values asserted to V; a value of another type is a CAST_FAILED error.
func PruneAll ¶
PruneAll prunes every registered model, stopping at the first failure. It returns the count per name.
func Push ¶
Push saves v and every relation loaded on it, depth first (Eloquent's push): a loaded belongs-to parent is saved first and v's foreign key follows it; loaded children are linked to v and saved after it. Everything runs in one transaction.
func Reduce ¶
func Reduce[T, A any](c Collection[T], initial A, fn func(acc A, m *T) A) A
Reduce folds the collection into one value.
func RegisterMorph ¶
RegisterMorph registers model T under alias (e.g. "post"). T must have a single primary key.
func RegisterPrunable ¶
RegisterPrunable lets PruneAll (and the model:prune command) find T.
func Replicate ¶
Replicate returns an unsaved copy of v (Eloquent's replicate): the primary key, creation and update times, the soft-delete mark, loaded relations and the columns named in except are cleared. The copy is bound to the same database, so Save inserts it. before:replicate listeners may abort it.
func ToMap ¶
ToMap serializes a bound model the way Eloquent's toArray does: column names as keys, casts' Get applied, Hidden / Visible applied, Appends added, loaded relations nested, extras (counts, pivot) included.
Types ¶
type BaseModel ¶
type BaseModel struct {
Record
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
}
BaseModel is an optional embeddable base with an auto-increment uint key, like Lucid's BaseModel.
type BelongsTo ¶
type BelongsTo[T any] struct { // contains filtered or unexported fields }
func (*BelongsTo[T]) Associate ¶
func (r *BelongsTo[T]) Associate(parent *T) error
Associate points the owner's foreign key at parent (it does not save the owner).
func (*BelongsTo[T]) Dissociate ¶
func (r *BelongsTo[T]) Dissociate() error
Dissociate clears the owner's foreign key (the column must be nullable; it does not save the owner).
func (*BelongsTo) Get ¶
Get returns the related row (nil when there is none), loading it on first use.
func (*BelongsTo) Item ¶
func (o *BelongsTo) Item() *T
Item returns the loaded row, or nil. A relation tagged orm:"withDefault" answers with an empty, unsaved model instead of nil once it has been loaded.
func (*BelongsTo) Query ¶
Query returns a query over the related table already constrained to this owner.
type BelongsToMany ¶
type BelongsToMany[T any] struct { // contains filtered or unexported fields }
func (*BelongsToMany[T]) Attach ¶
Attach links the given keys (or models), skipping links that already exist.
func (*BelongsToMany[T]) AttachWith ¶
AttachWith links keys and stores extra pivot columns on the new rows.
func (*BelongsToMany) Get ¶
func (m *BelongsToMany) Get(ctx context.Context) (Collection[T], error)
Get returns the related rows, loading them on first use.
func (*BelongsToMany) Items ¶
func (m *BelongsToMany) Items() Collection[T]
Items returns the loaded rows (empty until loaded; see Loaded).
func (*BelongsToMany) Query ¶
Query returns a query over the related table already constrained to this owner.
func (*BelongsToMany[T]) Sync ¶
func (r *BelongsToMany[T]) Sync(ctx context.Context, ids ...any) (SyncResult, error)
Sync makes the links exactly ids; SyncWithoutDetaching only adds.
func (*BelongsToMany[T]) SyncWithoutDetaching ¶
func (r *BelongsToMany[T]) SyncWithoutDetaching(ctx context.Context, ids ...any) (SyncResult, error)
func (*BelongsToMany[T]) Toggle ¶
func (r *BelongsToMany[T]) Toggle(ctx context.Context, ids ...any) (SyncResult, error)
func (*BelongsToMany[T]) UpdateExistingPivot ¶
type Cast ¶
Casts are Eloquent's mutators and accessors in one place. A model lists them per column:
func (User) Casts() map[string]orm.Cast {
return map[string]orm.Cast{"password": orm.CastHashed(), "settings": orm.CastJSON()}
}
Set runs when a value enters the model through Fill, Update, Make, CreateFrom or SetAttribute; Get runs when it leaves through ToMap, JSON or GetAttribute. Plain Go assignment (user.Name = "x") and Save are untouched: the struct field always holds the stored value.
func CastBool ¶
func CastBool() Cast
CastBool coerces on both sides: "1", "true", "on", "yes" and non-zero numbers are true.
func CastDate ¶
CastDate parses strings into time.Time on the way in and formats times on the way out, using layout (Eloquent's date / datetime:Y-m-d cast).
func CastEncrypted ¶
CastEncrypted encrypts a string with AES-GCM on Set and decrypts it on Get (Eloquent's encrypted cast). key must be 16, 24 or 32 bytes; a wrong size fails every use with CAST_FAILED. The stored value is base64 of nonce+ciphertext, so the column must be text. Changing the key makes existing rows unreadable.
func CastEnum ¶
CastEnum rejects any value outside values with CAST_FAILED before the row is written.
func CastFloat ¶
func CastFloat() Cast
CastFloat coerces numeric strings and integers to float64 on both sides.
func CastHashed ¶
func CastHashed() Cast
CastHashed bcrypt-hashes a string on Set (Eloquent's hashed cast). A value that already is a bcrypt hash is kept, so re-filling a loaded model does not hash twice. Get returns the hash: list the column in Hidden. Verify with CompareHash.
func CastHashedCost ¶
CastHashedCost is CastHashed with an explicit bcrypt cost.
type CastFunc ¶
CastFunc builds a cast from two functions; a nil side passes the value through. It is the way to write a custom accessor or mutator.
"email": orm.CastFunc{OnSet: func(v any) (any, error) { return strings.ToLower(fmt.Sprint(v)), nil }}
type Collection ¶
type Collection[T any] []T
Collection is a list of models with Eloquent's collection helpers. It is a defined slice type, so it indexes, ranges and appends like []T, and converts to and from []T freely.
Methods that read a column or the primary key need bound models (rows loaded through a query or a relation); on a collection of hand-built structs they return UNBOUND_MODEL.
func (Collection[T]) Contains ¶
func (c Collection[T]) Contains(id any) (bool, error)
Contains reports whether a model with that primary key is in the collection.
func (Collection[T]) Each ¶
func (c Collection[T]) Each(fn func(i int, m *T) error) error
Each calls fn for every model; returning an error stops the walk.
func (Collection[T]) Except ¶
func (c Collection[T]) Except(ids ...any) (Collection[T], error)
Except drops the models whose primary key is in ids.
func (Collection[T]) Filter ¶
func (c Collection[T]) Filter(keep func(m *T) bool) Collection[T]
Filter keeps the models for which keep returns true. The result holds copies that stay bound to the database (Save and lazy relations work on them), but edits to a copy do not show in the original collection.
func (Collection[T]) Find ¶
func (c Collection[T]) Find(id any) (*T, error)
Find returns the model with the given primary key, or nil. Keys compare by printed value, so 1, uint(1) and "1" match.
func (Collection[T]) First ¶
func (c Collection[T]) First() *T
First returns a pointer to the first model, or nil.
func (Collection[T]) Fresh ¶
func (c Collection[T]) Fresh(ctx context.Context) (Collection[T], error)
Fresh reloads the models from the database, keeping their order. Rows that no longer exist are dropped.
func (Collection[T]) GroupBy ¶
func (c Collection[T]) GroupBy(col string) (map[any]Collection[T], error)
GroupBy buckets the models by a column; NULLs are skipped.
func (Collection[T]) IsEmpty ¶
func (c Collection[T]) IsEmpty() bool
IsEmpty reports whether there are no models.
func (Collection[T]) JSON ¶
func (c Collection[T]) JSON(opts ...SerializeOpt) ([]byte, error)
JSON encodes the collection as a JSON array of serialized models.
func (Collection[T]) KeyBy ¶
func (c Collection[T]) KeyBy(col string) (map[any]T, error)
KeyBy indexes the models by a column. The map holds plain copies of the structs. The key keeps the field's Go type (uint for an ID), pointer columns are dereferenced and NULLs are skipped. Later duplicates win.
func (Collection[T]) Last ¶
func (c Collection[T]) Last() *T
Last returns a pointer to the last model, or nil.
func (Collection[T]) Load ¶
func (c Collection[T]) Load(ctx context.Context, relations ...string) error
Load eager-loads relations onto every model with one query per relation (Eloquent's load()).
func (Collection[T]) LoadMissing ¶
func (c Collection[T]) LoadMissing(ctx context.Context, relations ...string) error
LoadMissing loads a relation only onto the models that do not have it loaded yet.
func (Collection[T]) ModelKeys ¶
func (c Collection[T]) ModelKeys() ([]any, error)
ModelKeys returns the primary key of every model.
func (Collection[T]) Only ¶
func (c Collection[T]) Only(ids ...any) (Collection[T], error)
Only keeps the models whose primary key is in ids.
func (Collection[T]) Pluck ¶
func (c Collection[T]) Pluck(col string) ([]any, error)
Pluck returns one column of every model (Eloquent's pluck).
func (Collection[T]) Reject ¶
func (c Collection[T]) Reject(drop func(m *T) bool) Collection[T]
Reject is the inverse of Filter.
func (Collection[T]) ToMaps ¶
func (c Collection[T]) ToMaps(opts ...SerializeOpt) ([]map[string]any, error)
ToMaps serializes every model with ToMapWith.
func (Collection[T]) Unique ¶
func (c Collection[T]) Unique(col string) (Collection[T], error)
Unique keeps the first model of every distinct column value.
type ColumnInfo ¶
type ColumnInfo struct {
Name string
GoType string
DBType string
PrimaryKey bool
AutoIncrement bool
NotNull bool
Unique bool
HasDefault bool
}
ColumnInfo describes one column of a model.
type Connected ¶
type Connected interface{ Connection() string }
Connected lets a model say which Manager connection it lives on (Eloquent's $connection).
type CursorPage ¶
type CursorPage[T any] struct { Data Collection[T] PerPage int NextCursor string PrevCursor string }
CursorPage is one keyset page. Pass NextCursor or PrevCursor back to CursorPaginate; an empty cursor means there is no page in that direction.
type Defaults ¶
Defaults returns the values a model starts with when built through Model.Make or CreateFrom (Eloquent's $attributes). A struct literal is never touched: Go cannot tell a field left at its zero value from one set to it.
type Fillable ¶
type Fillable interface{ Fillable() []string }
Fillable lists the only columns Fill / CreateFrom may set (Eloquent's $fillable).
type GlobalScoped ¶
type GlobalScoped interface{ GlobalScopes() []NamedScope }
GlobalScoped is implemented by models that always filter (or order) their queries:
func (Post) GlobalScopes() []orm.NamedScope {
return []orm.NamedScope{{Name: "visible", Fn: func(g *gorm.DB) *gorm.DB { return g.Where("hidden = ?", false) }}}
}
Global scopes apply to Query, Find, FindMany, All, counts, updates, deletes and to eager-loaded relations of that model.
type Guarded ¶
type Guarded interface{ Guarded() []string }
Guarded lists columns Fill may not set (Eloquent's $guarded). Ignored when Fillable exists.
type HasMany ¶
type HasMany[T any] struct { // contains filtered or unexported fields }
func (*HasMany[T]) Create ¶
Create builds a child from attrs (mass assignment rules apply), links and inserts it.
func (*HasMany[T]) CreateMany ¶
CreateMany creates one child per attrs map, atomically.
func (*HasMany) Get ¶
func (m *HasMany) Get(ctx context.Context) (Collection[T], error)
Get returns the related rows, loading them on first use.
func (*HasMany) Items ¶
func (m *HasMany) Items() Collection[T]
Items returns the loaded rows (empty until loaded; see Loaded).
func (*HasMany) Query ¶
Query returns a query over the related table already constrained to this owner.
func (*HasMany[T]) Save ¶
Save sets the foreign key on child and persists it (Eloquent's $user->posts()->save($post)).
type HasManyThrough ¶
type HasManyThrough[T, Through any] struct { // contains filtered or unexported fields }
func (*HasManyThrough) Get ¶
func (m *HasManyThrough) Get(ctx context.Context) (Collection[T], error)
Get returns the related rows, loading them on first use.
func (*HasManyThrough) Items ¶
func (m *HasManyThrough) Items() Collection[T]
Items returns the loaded rows (empty until loaded; see Loaded).
type HasManyThroughLoader ¶
type HasManyThroughLoader[T any, Through any] struct { ForeignKey string ThroughLocalKey string ThroughForeignKey string // Scope optionally filters or orders the T query. Scope func(*gorm.DB) *gorm.DB }
HasManyThroughLoader loads T rows reachable from a parent via a Through model, like Lucid's hasManyThrough: Country -> User (Through) -> Post (T).
ForeignKey column on Through pointing at the parent (users.country_id) ThroughLocalKey Through's key referenced by T (users.id), default "id" ThroughForeignKey column on T pointing at Through (posts.user_id)
type HasOne ¶
type HasOne[T any] struct { // contains filtered or unexported fields }
func (*HasOne) Item ¶
func (o *HasOne) Item() *T
Item returns the loaded row, or nil. A relation tagged orm:"withDefault" answers with an empty, unsaved model instead of nil once it has been loaded.
func (*HasOne) Query ¶
Query returns a query over the related table already constrained to this owner.
type HasOneThrough ¶
type HasOneThrough[T, Through any] struct { // contains filtered or unexported fields }
HasOneThrough reaches a single T through an intermediate model (Eloquent's hasOneThrough).
func (*HasOneThrough) Get ¶
Get returns the related row (nil when there is none), loading it on first use.
func (*HasOneThrough) Item ¶
func (o *HasOneThrough) Item() *T
Item returns the loaded row, or nil. A relation tagged orm:"withDefault" answers with an empty, unsaved model instead of nil once it has been loaded.
func (*HasOneThrough) Query ¶
Query returns a query over the related table already constrained to this owner.
type Hidden ¶
type Hidden interface{ Hidden() []string }
Hidden lists columns left out of ToMap / JSON (Eloquent's $hidden).
type JSONColumn ¶
type JSONColumn[T any] struct{ Data T }
JSONColumn is a typed JSON column: the struct field holds a T and the database holds its JSON text (Eloquent's array / AsArrayObject cast, with the type checked by the compiler).
type User struct {
orm.BaseModel
Settings orm.JSONColumn[Settings]
}
user.Settings.Data.Theme = "dark"
A zero T (nil map, nil slice, nil pointer) is stored as NULL.
func (JSONColumn[T]) GormDBDataType ¶
GormDBDataType picks the native type per database.
func (JSONColumn[T]) GormDataType ¶
func (JSONColumn[T]) GormDataType() string
GormDataType tells GORM which column type to assume.
func (JSONColumn[T]) MarshalJSON ¶
func (j JSONColumn[T]) MarshalJSON() ([]byte, error)
MarshalJSON makes ToMap / JSON output the nested value, not {"Data": ...}.
func (*JSONColumn[T]) Scan ¶
func (j *JSONColumn[T]) Scan(src any) error
Scan implements sql.Scanner.
func (*JSONColumn[T]) UnmarshalJSON ¶
func (j *JSONColumn[T]) UnmarshalJSON(b []byte) error
UnmarshalJSON is the inverse of MarshalJSON.
type MassPrunable ¶
MassPrunable is Prunable deleted with one statement and no events (Eloquent's MassPrunable). When a model has both, MassPrunable wins.
type Model ¶
type Model[T any] struct { // contains filtered or unexported fields }
Model is the repository for T.
func Using ¶
Using returns the repository for T on the connection T names, or the manager's default:
func (AuditLog) Connection() string { return "audit" }
logs, err := orm.Using[AuditLog](ctx, manager)
func (*Model[T]) CreateFrom ¶
CreateFrom builds a model from attrs (mass assignment rules apply) and inserts it (Eloquent's Model::create).
func (*Model[T]) Destroy ¶
Destroy deletes rows by primary key (soft when the model soft deletes) and returns how many.
func (*Model[T]) Find ¶
Find loads by primary key; returns migro.ErrNotFound-matching error when missing.
func (*Model[T]) FindMany ¶
FindMany loads several rows by primary key; missing ids are simply absent.
func (*Model[T]) FindOrFail ¶
FindOrFail is Find: a missing row is already a NOT_FOUND error.
func (*Model[T]) FirstOrCreate ¶
FirstOrCreate finds a row matching the non-zero fields of where, or creates it with attrs applied. Returns whether a row was created.
func (*Model[T]) FirstOrCreateMany ¶
FirstOrCreateMany is UpdateOrCreateMany that leaves existing rows untouched (Lucid's fetchOrCreateMany).
func (*Model[T]) FirstOrNew ¶
FirstOrNew finds a row matching the non-zero fields of where, or returns an unsaved one built from where and attrs. Returns whether the row exists.
func (*Model[T]) InsertOrIgnore ¶
InsertOrIgnore inserts rows and silently skips the ones that violate a unique key.
func (*Model[T]) Make ¶
Make builds an unsaved model from attrs, honouring Fillable/Guarded (Eloquent's new Model($attrs)).
func (*Model[T]) Prune ¶
Prune deletes the model's stale rows for good, soft-deleted ones included, and returns how many.
func (*Model[T]) Query ¶
Query starts a fluent query.
Global scopes declared by the model (see GlobalScoped) are applied to it.
func (*Model[T]) Truncate ¶
Truncate empties the table (soft-deleted rows included). The statement is DELETE-based on SQLite, which has no TRUNCATE.
func (*Model[T]) UpdateOrCreate ¶
UpdateOrCreate finds by where and applies values, or creates the row with where+values.
func (*Model[T]) UpdateOrCreateMany ¶
UpdateOrCreateMany upserts each row by the given key columns, in one transaction (Lucid's updateOrCreateMany): an existing row gets the other fields of the row applied.
func (*Model[T]) Upsert ¶
Upsert inserts rows, and for a row whose uniqueBy columns already exist updates the update columns (all columns except the keys and created_at when update is empty), in one statement (Eloquent's upsert). uniqueBy needs a unique index. MySQL ignores uniqueBy and uses whichever unique key conflicts. SQL Server and Oracle run a MERGE; Redshift has no upsert and is refused.
type ModelInfo ¶
type ModelInfo struct {
Name string
Table string
SoftDeletes bool
Columns []ColumnInfo
Relations []RelationInfo
// Traits lists the optional behaviours the model opts into: Fillable, Hidden, Touches, ...
Traits []string
}
ModelInfo is what Describe reports (the model:show command prints it).
type MorphMany ¶
type MorphMany[T any] struct { // contains filtered or unexported fields }
func (*MorphMany[T]) CreateMany ¶
func (*MorphMany) Get ¶
func (m *MorphMany) Get(ctx context.Context) (Collection[T], error)
Get returns the related rows, loading them on first use.
func (*MorphMany) Items ¶
func (m *MorphMany) Items() Collection[T]
Items returns the loaded rows (empty until loaded; see Loaded).
func (*MorphMany) Query ¶
Query returns a query over the related table already constrained to this owner.
type MorphOne ¶
type MorphOne[T any] struct { // contains filtered or unexported fields }
func (*MorphOne) Get ¶
Get returns the related row (nil when there is none), loading it on first use.
func (*MorphOne) Item ¶
func (o *MorphOne) Item() *T
Item returns the loaded row, or nil. A relation tagged orm:"withDefault" answers with an empty, unsaved model instead of nil once it has been loaded.
func (*MorphOne) Query ¶
Query returns a query over the related table already constrained to this owner.
type MorphRegistry ¶
type MorphRegistry struct {
// contains filtered or unexported fields
}
MorphRegistry maps type aliases (the value stored in a *_type column) to model loaders. It is an instance, not a global, so each application wires its own.
func NewMorphRegistry ¶
func NewMorphRegistry() *MorphRegistry
type MorphTo ¶
type MorphTo struct {
// contains filtered or unexported fields
}
MorphTo is the inverse of MorphOne/MorphMany: the owner holds <name>_type and <name>_id, and the target is any model registered with MorphMap. Item is a pointer to that model.
func (*MorphTo) Get ¶
Get returns the target (nil when it no longer exists), loading it on first use.
type MorphToMany ¶
type MorphToMany[T any] struct { // contains filtered or unexported fields }
func (*MorphToMany[T]) AttachWith ¶
func (*MorphToMany) Get ¶
func (m *MorphToMany) Get(ctx context.Context) (Collection[T], error)
Get returns the related rows, loading them on first use.
func (*MorphToMany) Items ¶
func (m *MorphToMany) Items() Collection[T]
Items returns the loaded rows (empty until loaded; see Loaded).
func (*MorphToMany) Query ¶
Query returns a query over the related table already constrained to this owner.
func (*MorphToMany[T]) Sync ¶
func (r *MorphToMany[T]) Sync(ctx context.Context, ids ...any) (SyncResult, error)
func (*MorphToMany[T]) SyncWithoutDetaching ¶
func (r *MorphToMany[T]) SyncWithoutDetaching(ctx context.Context, ids ...any) (SyncResult, error)
type MorphToManyLoader ¶
type MorphToManyLoader[T any] struct { Pivot Pivot RelatedKey string Scope func(*gorm.DB) *gorm.DB }
MorphToManyLoader loads T (the related side, e.g. Tag) for polymorphic parents (e.g. Post). RelatedKey is T's key referenced by the pivot, default "id".
func (MorphToManyLoader[T]) Attach ¶
func (r MorphToManyLoader[T]) Attach(ctx context.Context, db *migro.DB, parentKey any, relatedKeys ...any) error
Attach links related keys to the parent, skipping links that already exist.
func (MorphToManyLoader[T]) Detach ¶
func (r MorphToManyLoader[T]) Detach(ctx context.Context, db *migro.DB, parentKey any, relatedKeys ...any) error
Detach removes the given links, or every link of the parent when no keys are passed.
type MorphedByMany ¶
type MorphedByMany[T any] struct { // contains filtered or unexported fields }
func (*MorphedByMany) Get ¶
func (m *MorphedByMany) Get(ctx context.Context) (Collection[T], error)
Get returns the related rows, loading them on first use.
func (*MorphedByMany) Items ¶
func (m *MorphedByMany) Items() Collection[T]
Items returns the loaded rows (empty until loaded; see Loaded).
func (*MorphedByMany) Query ¶
Query returns a query over the related table already constrained to this owner.
type MorphedByManyLoader ¶
type MorphedByManyLoader[T any] struct { Pivot Pivot MorphKey string Scope func(*gorm.DB) *gorm.DB }
MorphedByManyLoader is the inverse: given related keys (Tags), load the morphable T (Posts). MorphKey is T's key stored in the pivot, default "id".
type NamedScope ¶
NamedScope is a global scope. The name lets one query switch it off with WithoutGlobalScope.
type Pivot ¶
type Pivot struct {
Table string
MorphIDColumn string // taggable_id
MorphTypeCol string // taggable_type
RelatedIDCol string // tag_id
// MorphType is the alias stored in MorphTypeCol for the morphable side (e.g. "post").
MorphType string
}
Pivot describes a polymorphic pivot table, e.g. taggables(tag_id, taggable_id, taggable_type).
type PivotModels ¶
PivotModels lets a model say that a many-to-many relation's pivot rows are a struct of their own (Eloquent's using(Pivot::class)). Attach then creates each row through that struct, so its hooks run, its own key is generated (UUIDKey, a BeforeCreate) and its defaults apply. The map is keyed by the relation's field name; the value is the pivot struct or a pointer to it. The struct's columns must include the pivot's two keys and every column you pass to AttachWith.
func (User) PivotModels() map[string]any { return map[string]any{"Roles": RoleUser{}} }
type Prunable ¶
Prunable selects the stale rows of T that Prune deletes one by one, firing model events and ForceDelete semantics (Eloquent's Prunable):
func (Session) Prunable(q *orm.Query[Session]) *orm.Query[Session] { return q.Where("expires_at < ?", time.Now()) }
type Pruning ¶
Pruning is an optional hook run on each row before a Prunable delete, e.g. to remove its files.
type Query ¶
type Query[T any] struct { // contains filtered or unexported fields }
Query is a mutable, chainable query for model T.
func (*Query[T]) Chunk ¶
Chunk walks the result in primary-key order, size rows at a time, stopping at the first error. Rows are hydrated like Get (bound, With / WithCount applied).
func (*Query[T]) ChunkByID ¶
func (q *Query[T]) ChunkByID(ctx context.Context, size int, column string, fn func(rows []T) error) error
ChunkByID is Chunk keyed on column instead of the primary key (Eloquent's chunkById). The column must be unique and ascending-comparable; an empty column means the primary key.
func (*Query[T]) Cursor ¶
Cursor streams the rows one at a time through a single open statement (Eloquent's cursor): memory stays flat for huge results. Relations are not eager loaded; use Lazy when you need With. Breaking out of the loop closes the statement.
func (*Query[T]) CursorPaginate ¶
func (q *Query[T]) CursorPaginate(ctx context.Context, perPage int, cursor string) (CursorPage[T], error)
CursorPaginate pages by the query's OrderBy columns instead of an offset, so deep pages stay fast and rows inserted meanwhile do not shift the page. The query needs at least one OrderBy; the primary key is appended as a tie-breaker. Order columns must not be NULL.
func (*Query[T]) Delete ¶
Delete removes matching rows (soft when T has gorm.DeletedAt); GORM refuses without a Where.
func (*Query[T]) DoesntHave ¶
DoesntHave keeps models with no related row; WhereDoesntHave ignores rows outside scope.
func (*Query[T]) Each ¶
Each runs fn for every row, size rows at a time, stopping at the first error.
func (*Query[T]) FirstOrFail ¶
FirstOrFail is First: a missing row is already a NOT_FOUND error.
func (*Query[T]) FirstWhere ¶
FirstWhere is Where(col = value) followed by First.
func (*Query[T]) GroupBy ¶
GroupBy groups by columns; combine it with Select and Having for aggregates.
func (*Query[T]) Has ¶
Has keeps models that have at least one related row; WhereHas also constrains those rows.
func (*Query[T]) Having ¶
Having filters groups: Having("COUNT(*) > ?", 3). Never concatenate input into the condition.
func (*Query[T]) Latest ¶
Latest orders newest first by created_at (or the given column); Oldest is the opposite.
func (*Query[T]) Lazy ¶
Lazy streams the rows chunk by chunk (Eloquent's lazyById): each chunk is hydrated like Get, so With and WithCount work, and memory holds one chunk at a time.
func (*Query[T]) LockForUpdate ¶
LockForUpdate adds FOR UPDATE; SharedLock adds a shared row lock. Use them inside a transaction. SQLite ignores both (it locks the whole database); SQL Server and Oracle's shared lock are not supported and fail with UNSUPPORTED_FEATURE.
func (*Query[T]) OnlyTrashed ¶
OnlyTrashed returns only soft-deleted rows.
func (*Query[T]) OrWhereRaw ¶
OrWhereRaw is WhereRaw joined with OR.
func (*Query[T]) OrderByDesc ¶
func (*Query[T]) SharedLock ¶
func (*Query[T]) SimplePaginate ¶
SimplePaginate returns page (1-based) and whether a next page exists.
func (*Query[T]) Sole ¶
Sole returns the only match: NOT_FOUND for none, MULTIPLE_RECORDS_FOUND for several.
func (*Query[T]) ToSQL ¶
ToSQL renders the SELECT this query would run, with its bindings inlined, without running it (Eloquent's toRawSql). Use it for debugging; never feed the result back to the database.
func (*Query[T]) Union ¶
Union combines the receiver with others, removing duplicates; UnionAll keeps them. The result is a query over the combined rows: add OrderBy, Limit or Paginate to it afterwards. Each side keeps its own conditions and global scopes, and Select lists must line up.
func (*Query[T]) WhereBelongsTo ¶
WhereBelongsTo keeps the rows that belong to parent through a belongs-to relation (Eloquent's whereBelongsTo): posts.Query().WhereBelongsTo(user). With several relations to the same model, name the relation: WhereBelongsTo(user, "Editor").
func (*Query[T]) WhereColumn ¶
WhereColumn compares two columns: WhereColumn("updated_at", ">", "created_at").
func (*Query[T]) WhereDate ¶
WhereDate compares the date part of a date/time column (value is "2026-01-31" or a time.Time).
func (*Query[T]) WhereDoesntHave ¶
func (*Query[T]) WhereExists ¶
WhereExists adds EXISTS (sub). Correlate the subquery with WhereColumn:
users.Query().WhereExists(posts.Query().WhereColumn("e_posts.user_id", "=", "e_users.id"))
func (*Query[T]) WhereFullText ¶
WhereFullText matches a search text against columns that have a full-text index (see schema Table.FullText). MySQL uses MATCH AGAINST and PostgreSQL to_tsvector.
func (*Query[T]) WhereFullTextBoolean ¶
WhereFullTextBoolean is WhereFullText with operator syntax (+word -word "a phrase").
func (*Query[T]) WhereHasMorph ¶
WhereHasMorph keeps the rows whose morph-to relation points at one of the given morph aliases, and whose target satisfies scope (nil for any target): WhereHasMorph("Commentable", []string{"post"}, nil).
func (*Query[T]) WhereJSON ¶
WhereJSON compares the text at a JSON path inside col: WhereJSON("meta", "address.city", "=", "Rio"). Path segments are names or array indexes separated by dots.
func (*Query[T]) WhereNotExists ¶
WhereNotExists adds NOT EXISTS (sub).
func (*Query[T]) WhereNotLike ¶
func (*Query[T]) WhereNotNull ¶
func (*Query[T]) WhereRaw ¶
WhereRaw adds a raw condition. Pass values as args; never concatenate input into sql.
func (*Query[T]) WhereRelation ¶
WhereRelation is WhereHas with a plain condition: WhereRelation("Posts", "published = ?", true).
func (*Query[T]) WhereYear ¶
WhereYear, WhereMonth and WhereDay compare one component of a date/time column.
func (*Query[T]) With ¶
With eager-loads relations by field name; "Posts.Comments" nests. An optional scope constrains the last relation of the path: With("Posts", func(q *gorm.DB) *gorm.DB { return q.Where(...) }).
func (*Query[T]) WithCount ¶
WithCount adds "<relation>_count" to each model's Extras (Eloquent's withCount).
func (*Query[T]) WithExists ¶
WithExists adds "<relation>_exists" (a bool) to each model's Extras.
func (*Query[T]) WithSum ¶
WithSum, WithAvg, WithMin and WithMax add an aggregate of a related column to each model's Extras as "<relation>_sum_<column>" (and so on), computed in one extra query. Sum is 0 when nothing is related; the others are nil. Supported on has-one/many, morph one/many and the many-to-many kinds.
func (*Query[T]) WithTrashed ¶
WithTrashed includes soft-deleted rows.
func (*Query[T]) WithoutGlobalScope ¶
WithoutGlobalScope switches the named global scopes off for this query.
func (*Query[T]) WithoutGlobalScopes ¶
WithoutGlobalScopes switches every global scope off for this query.
type R ¶
type R struct {
// contains filtered or unexported fields
}
R collects the fields of one resource item.
type Record ¶
type Record struct {
// contains filtered or unexported fields
}
Record carries the active-record behaviour (Save, Delete, Refresh, Fill, IsDirty, relations, ...) without any column. BaseModel, UUIDModel and ULIDModel embed it and add a primary key; embed it yourself to bring your own key.
Models returned by Model[T] / Query[T] are bound to their database, which enables the instance methods and lazy relations. A struct you build by hand is unbound until you create it through the repository or call Bind.
func (*Record) Delete ¶
Delete removes the row, or marks it deleted when the model has a gorm.DeletedAt column.
func (*Record) DeleteQuietly ¶
DeleteQuietly is Delete without model events.
func (*Record) Extras ¶
Extras holds computed values attached by queries: "<relation>_count" from WithCount and "pivot_<column>" on models loaded through a many-to-many relation (Lucid's $extras).
func (*Record) Fill ¶
Fill sets columns (by column or field name) from attrs. Fields outside Fillable, or inside Guarded, fail with MASS_ASSIGNMENT instead of being silently dropped. Models implementing neither are open.
func (*Record) ForceDelete ¶
ForceDelete removes the row for good, soft deletes included.
func (*Record) GetAttribute ¶
GetAttribute returns one column through its cast (an accessor).
func (*Record) GetChanges ¶
GetChanges returns the columns the last Save wrote, with their new values.
func (*Record) GetOriginal ¶
GetOriginal returns the value a column had when the model was loaded or last saved.
func (*Record) Increment ¶
Increment adds n to a numeric column atomically in SQL, then reloads the model.
func (*Record) IncrementEach ¶
IncrementEach adds a different amount to several columns in one atomic UPDATE, then reloads the model.
func (*Record) IsDirty ¶
IsDirty reports whether any (or, when given, any of the named) columns changed since load/save.
func (*Record) Save ¶
Save inserts a new model, or updates only the columns that changed since it was loaded (Eloquent's save). A model with no changes issues no query.
func (*Record) SaveQuietly ¶
SaveQuietly is Save without model events (Eloquent's saveQuietly).
func (*Record) SaveWithoutTimestamps ¶
SaveWithoutTimestamps saves without touching updated_at, and without events or hooks (Eloquent's withoutTimestamps). A new row is inserted with the timestamps it already carries.
func (*Record) SetAttribute ¶
SetAttribute sets one column through its cast (a mutator), ignoring Fillable / Guarded: it is the programmatic counterpart of `$model->column = value`.
func (*Record) UseTransaction ¶
UseTransaction rebinds the model to tx, so its next Save, Delete or lazy load runs inside the transaction (Lucid's useTransaction). Relations already loaded stay loaded.
func (*Record) WasChanged ¶
WasChanged reports whether the last Save wrote any (or, when given, any of the named) columns. A Save that inserted the row counts every column as changed.
func (*Record) WasRecentlyCreated ¶
WasRecentlyCreated reports whether the last Save inserted the row.
type RelationInfo ¶
type RelationInfo struct {
Name string
Kind string // has_one, has_many, belongs_to, belongs_to_many, ...
Related string // the related model, "(any)" for morph-to
// Keys spells out how the relation joins, e.g. "posts.user_id -> users.id".
Keys string
}
RelationInfo describes one relation of a model.
type Resource ¶
type Resource[T any] struct { // contains filtered or unexported fields }
Resource turns a model into the exact shape your API returns, the way Laravel's JsonResource does. Unlike ToMap, nothing is exposed unless you list it.
var UserResource = orm.NewResource(func(u *User, r *orm.R) {
r.Set("id", u.ID)
r.Set("name", u.Name)
r.When(isAdmin, "email", u.Email)
r.WhenLoaded("Posts", func() (any, error) { return PostResource.List(u.Posts.Items()) })
})
body, err := UserResource.Make(user) // {"data": {...}}
body, err = UserResource.Collection(users) // {"data": [...]}
body, err = UserResource.Paginated(page) // {"data": [...], "meta": {...}}
func NewResource ¶
NewResource builds a resource from a function that describes one model.
func (*Resource[T]) Additional ¶
Additional adds top-level keys next to the wrapped payload (Laravel's additional()).
func (*Resource[T]) Collection ¶
Collection is the response for a list.
func (*Resource[T]) Map ¶
Map describes one model without any wrapping: use it to nest a resource inside another.
func (*Resource[T]) Paginated ¶
Paginated is the response for a page: the items plus "meta" (current_page, last_page, per_page, total, from, to). Pass a base URL to also get "links" (first, last, prev, next).
func (*Resource[T]) WithoutWrapping ¶
WithoutWrapping returns the bare item (Make) or array (Collection). Extra top-level keys (Additional, Paginated's meta) merge into a bare item; a bare array that has to carry them keeps its wrapper.
type SerializeAs ¶
SerializeAs renames columns and relations in ToMap / JSON: {"created_at": "createdAt"} (Lucid's serializeAs).
type SerializeOpt ¶
type SerializeOpt func(*serializeCfg)
SerializeOpt adjusts one ToMapWith / JSONWith call.
func DateFormat ¶
func DateFormat(layout string) SerializeOpt
DateFormat renders time.Time values with a Go layout, nested relations included.
func MakeHidden ¶
func MakeHidden(cols ...string) SerializeOpt
MakeHidden hides extra columns for this call only (Eloquent's makeHidden). It wins over MakeVisible.
func MakeVisible ¶
func MakeVisible(cols ...string) SerializeOpt
MakeVisible shows columns the model hides, for this call only (Eloquent's makeVisible).
type SimplePage ¶
type SimplePage[T any] struct { Data Collection[T] PerPage int CurrentPage int HasMore bool }
SimplePage is a page without a total: one extra row tells whether another page follows, so it skips the COUNT query Paginate pays for.
type SoftDeleteModel ¶
SoftDeleteModel adds soft deletes: Delete sets DeletedAt and queries hide those rows.
type SoftDeleteULIDModel ¶
SoftDeleteULIDModel is ULIDModel with soft deletes.
type SoftDeleteUUIDModel ¶
SoftDeleteUUIDModel is UUIDModel with soft deletes.
type SubQuery ¶
type SubQuery interface {
// contains filtered or unexported methods
}
SubQuery is any Query[S]; it lets WhereExists take a query over another model.
type SyncResult ¶
type SyncResult struct{ Attached, Detached []any }
SyncResult reports what Sync / Toggle changed.
type Touches ¶
type Touches interface{ Touches() []string }
Touches lists belongs-to relations whose parent gets a fresh updated_at whenever this model is created, saved, deleted or restored through the repository or the instance methods (Eloquent's $touches). Bulk query updates do not touch, as in Eloquent.
type ULIDKey ¶
type ULIDKey struct {
ID string `gorm:"primaryKey;size:26"`
}
ULIDKey is UUIDKey with a 26-character ULID (Eloquent's HasUlids).
type ULIDModel ¶
type ULIDModel struct {
Record
ID string `gorm:"primaryKey;size:26"`
CreatedAt time.Time
UpdatedAt time.Time
}
ULIDModel is BaseModel with a 26-character ULID key (Eloquent's HasUlids).
type UUIDKey ¶
type UUIDKey struct {
ID string `gorm:"primaryKey;size:36"`
}
UUIDKey is an embeddable primary key that fills itself with a time-ordered UUID (version 7) on insert (Eloquent's HasUuids). It is the bare key: embed UUIDModel instead to also get the timestamps and the instance methods (Save, Delete, ...). A BeforeCreate hook on the model itself replaces this one.
Source Files
¶
- cast.go
- collection.go
- connection.go
- describe.go
- entity.go
- fill.go
- json.go
- keys.go
- meta.go
- model.go
- model_bulk.go
- prune.go
- query.go
- query_cursor.go
- query_ext.go
- query_where.go
- relation_aggregate.go
- relation_extras.go
- relation_load.go
- relation_types.go
- relation_where.go
- relation_write.go
- relations.go
- replicate.go
- resource.go
- scope.go
- typecache.go