Help us shape the future of Go! Take the 2026 Go Developer Survey

gorm

package
v1.20.0-alpha.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

Package gorm contains the GORM-backed implementation of the framework's database/orm contracts.

Where the upstream framework has first-class Relation objects with `getRelationExistenceQuery` / `getRelationExistenceCountQuery` methods, GORM models its relationships through struct-tag metadata. The two are bridged here by relation.go's resolver: it inspects gorm.Schema and a model's optional ModelWithThroughRelations declaration, then produces a relationDescriptor that knows how to emit a correlated EXISTS / count subquery for any of HasOne, HasMany, BelongsTo, BelongsToMany, MorphOne, MorphMany, HasOneThrough or HasManyThrough.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Conditions

type Conditions struct {
	// contains filtered or unexported fields
}

Conditions holds the state that belongs to the ORM layer rather than to the SQL builder: the model and destination a statement addresses, eager loads, relationship subqueries, scopes, soft-delete switches and a few write-path filters. The SQL clauses themselves — select, where, join, group, having, order, limit, offset, distinct and lock — live on the Query's persistent builder, the way Laravel keeps them on Query\Builder. Conditions deliberately has no second copy of them.

type Event

type Event struct {
	// contains filtered or unexported fields
}

func NewEvent

func NewEvent(query *Query, model, dest any) *Event

func (*Event) Context

func (e *Event) Context() context.Context

func (*Event) GetAttribute

func (e *Event) GetAttribute(key string) any

func (*Event) GetOriginal

func (e *Event) GetOriginal(key string, def ...any) any

func (*Event) IsClean

func (e *Event) IsClean(fields ...string) bool

func (*Event) IsDirty

func (e *Event) IsDirty(columns ...string) bool

func (*Event) Query

func (e *Event) Query() orm.Query

Query returns a fresh query for the handler to build on. It is seeded from the same connection and transaction as the query that raised the event, so anything the handler writes joins that transaction rather than running beside it.

func (*Event) SetAttribute

func (e *Event) SetAttribute(key string, value any)

type Query

type Query struct {
	// contains filtered or unexported fields
}

func BuildQuery

func BuildQuery(ctx context.Context, config config.Config, connection string, log log.Log, modelToObserver []contractsorm.ModelToObserver, telemetryResolver contractstelemetry.Resolver) (*Query, contractsdatabase.Config, error)

func NewQuery

func NewQuery(
	ctx context.Context,
	config config.Config,
	dbConfig contractsdatabase.Config,
	writer *sql.DB,
	tx *sql.Tx,
	grammar contractsdriver.Grammar,
	log log.Log,
	modelToObserver []contractsorm.ModelToObserver,
	conditions *Conditions,
	telemetryResolver contractstelemetry.Resolver,
	supplied ...databasedriver.QueryComponents,
) *Query

func (*Query) AssociateRelation

func (r *Query) AssociateRelation(parent any, relation string, owner any) error

AssociateRelation sets parent's foreign key (and morph_type for MorphTo) to point at owner, then persists parent. Supported kinds: BelongsTo, MorphTo. owner must be a non-nil pointer to a struct.

Public Query-level helper used by Orm.Associate.

func (*Query) AttachRelation

func (r *Query) AttachRelation(parent any, relation string, ids []any) error

AttachRelation inserts pivot rows linking parent to each id in ids. Skips ids that already have a pivot row. Supported kinds: Many2Many, MorphToMany, MorphedByMany.

Public Query-level helper used by Orm.Attach.

func (*Query) AttachWithPivotRelation

func (r *Query) AttachWithPivotRelation(parent any, relation string, idsWithAttrs map[any]map[string]any) error

AttachWithPivotRelation is Attach with per-row pivot column values.

func (*Query) Avg

func (r *Query) Avg(column string, dest any) error

func (*Query) Begin

func (r *Query) Begin() (contractsorm.Query, error)

DEPRECATED Use BeginTransaction instead.

func (*Query) BeginTransaction

func (r *Query) BeginTransaction() (contractsorm.Query, error)

func (*Query) Clone

func (r *Query) Clone() contractsorm.Query

Clone returns an independent copy of the query: it shares the connection, grammar and observers, but owns its conditions and its builder, so clauses written to it never reach the receiver. It is what Orm.Query() hands a caller, mirroring Laravel's Connection::query(), which builds a new Query\Builder on every call.

func (*Query) Commit

func (r *Query) Commit() error

func (*Query) ConnectionIsCurrent

func (r *Query) ConnectionIsCurrent() bool

ConnectionIsCurrent lets the ORM facade evict a cached query after its logical connection was purged through another facade. Queries constructed directly without a managed handle are valid.

func (*Query) Context

func (r *Query) Context() context.Context

func (*Query) Count

func (r *Query) Count() (int64, error)

func (*Query) Create

func (r *Query) Create(value any) error

func (*Query) CreateManyRelation

func (r *Query) CreateManyRelation(parent any, relation string, dests any) error

CreateManyRelation is the slice form of CreateRelation. dests must be a slice or a pointer to a slice; iterates and calls CreateRelation per element, bailing on the first error.

func (*Query) CreateRelation

func (r *Query) CreateRelation(parent any, relation string, dest any) error

CreateRelation persists a new related row. For HasOneOrMany kinds (HasOne, HasMany, MorphOne, MorphMany) the framework first sets the FK (and morph type column) on dest from parent, then inserts. dest must be a non-nil pointer to a struct of the related type.

Public Query-level helper used by Orm.Create.

func (*Query) Cursor

func (r *Query) Cursor() chan contractsdb.Row

func (*Query) CursorPaginate

func (r *Query) CursorPaginate(perPage int, cursor string, dest any) (contractsdb.CursorPaginator, error)

CursorPaginate fetches one keyset ("seek") page and scans it into dest, which must be a pointer to a slice: a *[]map[string]any for an untyped page, or a pointer to a slice of structs for a typed one. cursor is the encoded anchor — an empty string is the first page, and a non-empty malformed string is refused with errors.QueryCursorInvalid rather than silently restarting.

The statement runs exactly once and is never counted. Unlike Paginate there is no total; the page carries only the rows and the cursors that reach its neighbours.

func (*Query) DB

func (r *Query) DB() (*sql.DB, error)

func (*Query) Decrement

func (r *Query) Decrement(column string, args ...any) (*contractsdb.Result, error)

Decrement subtracts amount (default 1) from the column of every matching row, refreshing the model's updated-at column and writing any extra values. Mirrors Builder::decrement.

func (*Query) Delete

func (r *Query) Delete(dests ...any) (*contractsdb.Result, error)

func (*Query) DetachRelation

func (r *Query) DetachRelation(parent any, relation string, ids []any) (int64, error)

DetachRelation removes pivot rows linking parent to the given ids. With nil/empty ids, removes all pivot rows for parent (and morph type, for polymorphic). Returns the number of rows removed.

func (*Query) DissociateRelation

func (r *Query) DissociateRelation(parent any, relation string) error

DissociateRelation clears parent's foreign key (and morph_type for MorphTo) and persists parent. Supported kinds: BelongsTo, MorphTo.

func (*Query) Distinct

func (r *Query) Distinct(columns ...string) contractsorm.Query

func (*Query) DoesntHave

func (r *Query) DoesntHave(relation string, args ...any) contractsorm.Query

DoesntHave adds a relationship absence condition to the query. Equivalent to Has(rel, "<", 1).

func (*Query) DoesntHaveMorph

func (r *Query) DoesntHaveMorph(relation string, types []any, args ...any) contractsorm.Query

DoesntHaveMorph adds a polymorphic relationship absence condition.

func (*Query) Driver

func (r *Query) Driver() string

func (*Query) Except

func (r *Query) Except(models any) contractsorm.Query

Except excludes the given models by primary key. Mirrors Builder::except, which is whereKeyNot over the models' keys.

func (*Query) Exec

func (r *Query) Exec(statement string, values ...any) (*contractsdb.Result, error)

Exec runs a statement the caller wrote. The statement is passed through untouched apart from the dialect's placeholder style, so a caller can use it for DDL and for anything the builder does not cover.

func (*Query) Exists

func (r *Query) Exists() (bool, error)

func (*Query) Find

func (r *Query) Find(dest any, conds ...any) error

func (*Query) FindMany

func (r *Query) FindMany(dest any, ids []any, columns ...any) error

FindMany retrieves the rows whose primary key is one of ids. Mirrors Builder::findMany: an empty list reads nothing.

func (*Query) FindOr

func (r *Query) FindOr(dest any, id any, callback func() error) error

FindOr retrieves the first row whose key matches id, or runs the callback when there is none, mirroring Laravel's Builder::findOr. It is Find's read with FirstOr's missing-row behaviour.

func (*Query) FindOrFail

func (r *Query) FindOrFail(dest any, conds ...any) error

func (*Query) FindOrNewRelation

func (r *Query) FindOrNewRelation(parent any, relation string, id any, dest any) error

FindOrNewRelation finds the related row with primary key id. If absent, fills dest with a new instance of the related model and pre-sets the FK (and morph type) — but does NOT persist. dest must be a pointer to a struct.

func (*Query) First

func (r *Query) First(dest any) error

func (*Query) FirstOr

func (r *Query) FirstOr(dest any, callback func() error) error

func (*Query) FirstOrCreate

func (r *Query) FirstOrCreate(dest any, conds ...any) error

func (*Query) FirstOrCreateRelation

func (r *Query) FirstOrCreateRelation(parent any, relation string, attrs map[string]any, values map[string]any, dest any) error

FirstOrCreateRelation is FirstOrNewRelation that persists when no matching row exists.

func (*Query) FirstOrFail

func (r *Query) FirstOrFail(dest any) error

func (*Query) FirstOrNew

func (r *Query) FirstOrNew(dest any, attributes any, values ...any) error

FirstOrNew looks a model up and, finding none, prepares one instead of storing it: the destination is filled from the query's own equalities and from the attributes, and nothing is written.

func (*Query) FirstOrNewRelation

func (r *Query) FirstOrNewRelation(parent any, relation string, attrs map[string]any, values map[string]any, dest any) error

FirstOrNewRelation finds the first related row matching attrs. If absent, fills dest with a new instance carrying attrs+values and pre-set FK — does NOT persist.

func (*Query) ForceDelete

func (r *Query) ForceDelete(dests ...any) (*contractsdb.Result, error)

func (*Query) Get

func (r *Query) Get(dest any, columns ...any) error

Get retrieves every matching row into dest.

A column list may be passed for this call only, mirroring Laravel's Builder::get($columns): the columns render into this statement's select list, but the query keeps the selection it already had — and it only takes the columns when it had none — so a statement compiled afterwards is unchanged.

func (*Query) Group

func (r *Query) Group(column string) contractsorm.Query

DEPRECATED Use GroupBy instead.

func (*Query) GroupBy

func (r *Query) GroupBy(column ...string) contractsorm.Query

func (*Query) Has

func (r *Query) Has(relation string, args ...any) contractsorm.Query

Has adds a relationship count / exists condition to the query.

args may include any combination of a RelationCallback (or func(Query) Query) for scoping the inner subquery, a string operator (defaults to ">="), and an int count (defaults to 1). For nested relations dot-notation is honoured: `Has("Books.Author")` is shorthand for `WhereHas("Books", q -> q.Has("Author"))`.

func (*Query) HasMorph

func (r *Query) HasMorph(relation string, types []any, args ...any) contractsorm.Query

HasMorph adds a polymorphic relationship count / exists condition to the query. types is a slice of model instances; the morph value used in the polymorphic type column is derived from each model's GORM-resolved table name.

Note: auto-discovery of distinct morph values via `types = ['*']` is not supported; an explicit list of model instances is required.

func (*Query) Having

func (r *Query) Having(query any, args ...any) contractsorm.Query

func (*Query) InRandomOrder

func (r *Query) InRandomOrder() contractsorm.Query

func (*Query) InTransaction

func (r *Query) InTransaction() bool

func (*Query) Increment

func (r *Query) Increment(column string, args ...any) (*contractsdb.Result, error)

Increment adds amount (default 1) to the column of every matching row, refreshing the model's updated-at column and writing any extra values. Mirrors Builder::increment: args are an optional amount followed by an optional map of extra columns.

func (*Query) Join

func (r *Query) Join(query string, args ...any) contractsorm.Query

func (*Query) Latest

func (r *Query) Latest(column ...string) contractsorm.Query

Latest orders by the column descending, defaulting to the model's created-at column. Mirrors Builder::latest.

func (*Query) LatestOfMany

func (r *Query) LatestOfMany(column ...string) contractsorm.Query

func (*Query) Limit

func (r *Query) Limit(limit int) contractsorm.Query

func (*Query) Load

func (r *Query) Load(model any, relation string, args ...any) error

Load lazily loads the named relation onto an already-populated model, the way Laravel's Model::load() does. The relation is eager-loaded against the model instance itself: the instance's primary key supplies the keys the related query is constrained by, so the model's own table is never re-read and a Load issued from an unconstrained query still attaches the receiver's own relations rather than whichever row the table happens to return first.

func (*Query) LoadMissing

func (r *Query) LoadMissing(model any, relation string, args ...any) error

func (*Query) LockForUpdate

func (r *Query) LockForUpdate() contractsorm.Query

func (*Query) Max

func (r *Query) Max(column string, dest any) error

func (*Query) Min

func (r *Query) Min(column string, dest any) error

func (*Query) Model

func (r *Query) Model(value any) contractsorm.Query

func (*Query) Observe

func (r *Query) Observe(model any, observer contractsorm.Observer)

func (*Query) OfMany

func (r *Query) OfMany(column, aggregate string) contractsorm.Query

func (*Query) Offset

func (r *Query) Offset(offset int) contractsorm.Query

func (*Query) Oldest

func (r *Query) Oldest(column ...string) contractsorm.Query

Oldest orders by the column ascending, defaulting to the model's created-at column. Mirrors Builder::oldest.

func (*Query) OldestOfMany

func (r *Query) OldestOfMany(column ...string) contractsorm.Query

func (*Query) Omit

func (r *Query) Omit(columns ...string) contractsorm.Query

func (*Query) OnlyTrashed

func (r *Query) OnlyTrashed() contractsorm.Query

func (*Query) OrDoesntHave

func (r *Query) OrDoesntHave(relation string, args ...any) contractsorm.Query

OrDoesntHave adds a relationship absence condition with an "or" conjunction.

func (*Query) OrDoesntHaveMorph

func (r *Query) OrDoesntHaveMorph(relation string, types []any, args ...any) contractsorm.Query

OrDoesntHaveMorph adds a polymorphic relationship absence condition with an "or" conjunction.

func (*Query) OrHas

func (r *Query) OrHas(relation string, args ...any) contractsorm.Query

OrHas adds a relationship count / exists condition to the query with an "or" conjunction.

func (*Query) OrHasMorph

func (r *Query) OrHasMorph(relation string, types []any, args ...any) contractsorm.Query

OrHasMorph adds a polymorphic relationship count / exists condition with an "or" conjunction.

func (*Query) OrWhere

func (r *Query) OrWhere(query any, args ...any) contractsorm.Query

func (*Query) OrWhereBelongsTo

func (r *Query) OrWhereBelongsTo(related any, relation ...string) contractsorm.Query

OrWhereBelongsTo is WhereBelongsTo with an "or" conjunction. Mirrors orWhereBelongsTo.

func (*Query) OrWhereBetween

func (r *Query) OrWhereBetween(column string, x, y any) contractsorm.Query

func (*Query) OrWhereDoesntHave

func (r *Query) OrWhereDoesntHave(relation string, args ...any) contractsorm.Query

OrWhereDoesntHave adds a relationship absence condition with where clauses and an "or" conjunction.

func (*Query) OrWhereDoesntHaveMorph

func (r *Query) OrWhereDoesntHaveMorph(relation string, types []any, args ...any) contractsorm.Query

OrWhereDoesntHaveMorph adds a polymorphic absence condition with where clauses and an "or" conjunction.

func (*Query) OrWhereDoesntHaveRelation

func (r *Query) OrWhereDoesntHaveRelation(relation string, column any, args ...any) contractsorm.Query

OrWhereDoesntHaveRelation is WhereDoesntHaveRelation with an "or" conjunction. Mirrors orWhereDoesntHaveRelation.

func (*Query) OrWhereHas

func (r *Query) OrWhereHas(relation string, args ...any) contractsorm.Query

OrWhereHas adds a relationship count / exists condition with where clauses and an "or" conjunction.

func (*Query) OrWhereHasMorph

func (r *Query) OrWhereHasMorph(relation string, types []any, args ...any) contractsorm.Query

OrWhereHasMorph adds a polymorphic existence condition with where clauses and an "or" conjunction.

func (*Query) OrWhereIn

func (r *Query) OrWhereIn(column string, values []any) contractsorm.Query

func (*Query) OrWhereJsonContains

func (r *Query) OrWhereJsonContains(column string, value any) contractsorm.Query

func (*Query) OrWhereJsonContainsKey

func (r *Query) OrWhereJsonContainsKey(column string) contractsorm.Query

func (*Query) OrWhereJsonDoesntContain

func (r *Query) OrWhereJsonDoesntContain(column string, value any) contractsorm.Query

func (*Query) OrWhereJsonDoesntContainKey

func (r *Query) OrWhereJsonDoesntContainKey(column string) contractsorm.Query

func (*Query) OrWhereJsonLength

func (r *Query) OrWhereJsonLength(column string, args ...any) contractsorm.Query

func (*Query) OrWhereNotBetween

func (r *Query) OrWhereNotBetween(column string, x, y any) contractsorm.Query

func (*Query) OrWhereNotIn

func (r *Query) OrWhereNotIn(column string, values []any) contractsorm.Query

func (*Query) OrWhereNull

func (r *Query) OrWhereNull(column string) contractsorm.Query

func (*Query) OrWhereRelation

func (r *Query) OrWhereRelation(relation string, column any, args ...any) contractsorm.Query

OrWhereRelation is WhereRelation with an "or" conjunction. Mirrors orWhereRelation.

func (*Query) Order

func (r *Query) Order(value any) contractsorm.Query

DEPRECATED: Use OrderByRaw instead

func (*Query) OrderBy

func (r *Query) OrderBy(column string, direction ...string) contractsorm.Query

func (*Query) OrderByDesc

func (r *Query) OrderByDesc(column string) contractsorm.Query

func (*Query) OrderByRaw

func (r *Query) OrderByRaw(raw string) contractsorm.Query

func (*Query) Paginate

func (r *Query) Paginate(page, limit int, dest any, total *int64) error

Paginate retrieves one page of rows, writing the total into total when it is not nil. It mirrors Laravel's Builder::paginate: a non-positive page and limit fall back to the defaults of page 1 and 15 rows, a total already carried by the caller is an override that skips the count, and a zero total skips the page fetch (Laravel returns an empty collection when the count is zero).

func (*Query) Pluck

func (r *Query) Pluck(column string, dest any) error

func (*Query) Raw

func (r *Query) Raw(sql string, values ...any) contractsorm.Query

func (*Query) Related

func (r *Query) Related(parent any, relation string) contractsorm.Query

Related is the public Query-level entry point. The Orm-level entry (Orm.Related) delegates here. Returns a fresh Query pre-scoped to the related rows for parent.relation.

func (*Query) Relation

func (r *Query) Relation(parent any, name string) contractsorm.RelationWriter

Relation returns a RelationWriter bound to the given parent and relation name. The returned builder forwards all write operations to the receiver's session, so calls inside a Transaction callback honor the transaction.

func (*Query) Restore

func (r *Query) Restore(dests ...any) (*contractsdb.Result, error)

func (*Query) Rollback

func (r *Query) Rollback() error

func (*Query) Save

func (r *Query) Save(dest any) error

func (*Query) SaveManyRelation

func (r *Query) SaveManyRelation(parent any, relation string, children any) error

SaveManyRelation is the slice form of SaveRelation. children must be a slice or pointer-to- slice of either pointer-to-struct or struct elements. Iterates and bails on first error.

func (*Query) SaveManyRelationWithPivot

func (r *Query) SaveManyRelationWithPivot(parent any, relation string, children any, attrsPerChild map[any]map[string]any) error

SaveManyRelationWithPivot is the slice form of SaveRelationWithPivot. attrsPerChild is keyed by the related PK of each child; an entry may be nil to attach without extra columns.

func (*Query) SaveQuietly

func (r *Query) SaveQuietly(value any) error

func (*Query) SaveRelation

func (r *Query) SaveRelation(parent any, relation string, child any) error

SaveRelation inserts or updates child as a member of parent's relation. Sets child's foreign key (and morph_type for MorphOne/MorphMany) from parent's local key, then persists child via Query.Save. For BelongsToMany kinds (Many2Many, MorphToMany, MorphedByMany) persists child first, then writes a pivot row linking parent and child.

Public Query-level helper used by Orm.Save. Named "SaveRelation" to avoid clashing with the existing single-arg Query.Save(value any) which persists a model directly.

Supported kinds: HasOne, HasMany, MorphOne, MorphMany, Many2Many, MorphToMany, MorphedByMany. Other kinds error with OrmRelationKindNotSupported.

func (*Query) SaveRelationWithPivot

func (r *Query) SaveRelationWithPivot(parent any, relation string, child any, attrs map[string]any) error

SaveRelationWithPivot is SaveRelation with caller-supplied pivot column values for the BelongsToMany family. On HasOneOrMany kinds attrs is ignored (no pivot row).

func (*Query) Scan

func (r *Query) Scan(dest any) error

func (*Query) Scopes

func (r *Query) Scopes(funcs ...func(contractsorm.Query) contractsorm.Query) contractsorm.Query

func (*Query) Select

func (r *Query) Select(columns ...string) contractsorm.Query

Select replaces the selected columns and their bindings, mirroring Laravel's select().

func (*Query) SelectRaw

func (r *Query) SelectRaw(query any, args ...any) contractsorm.Query

func (*Query) SharedLock

func (r *Query) SharedLock() contractsorm.Query

func (*Query) Sole

func (r *Query) Sole(dest any) error

Sole retrieves the one row the query matches. Mirrors BuildsQueries::sole: the statement is limited to two rows, so no row and more than one row are each reported as their own error.

func (*Query) Sum

func (r *Query) Sum(column string, dest any) error

func (*Query) SyncRelation

func (r *Query) SyncRelation(parent any, relation string, ids []any) (*dbcontract.SyncResult, error)

SyncRelation replaces parent's pivot rows so they exactly match ids: detaches missing entries, attaches new ones, leaves existing untouched. Returns the per-id outcome.

Public Query-level helper used by Orm.Sync.

func (*Query) SyncRelationWithPivot

func (r *Query) SyncRelationWithPivot(parent any, relation string, idsWithAttrs map[any]map[string]any) (*dbcontract.SyncResult, error)

SyncRelationWithPivot is SyncRelation with per-ID pivot column values. The map key is the related id; the map value is the column-name-to-value map applied to that pivot row. For existing pivot rows with non-empty attrs, updates the pivot columns (reported in SyncResult.Updated). Mirrors fedaco's sync(map).

func (*Query) SyncRelationWithPivotValues

func (r *Query) SyncRelationWithPivotValues(parent any, relation string, ids []any, pivotValues map[string]any) (*dbcontract.SyncResult, error)

SyncRelationWithPivotValues applies the same pivot column values to all ids. Mirrors fedaco's syncWithPivotValues.

func (*Query) SyncWithoutDetachingRelation

func (r *Query) SyncWithoutDetachingRelation(parent any, relation string, ids []any) (*dbcontract.SyncResult, error)

SyncWithoutDetachingRelation is SyncRelation minus the detach step.

func (*Query) SyncWithoutDetachingRelationWithPivot

func (r *Query) SyncWithoutDetachingRelationWithPivot(parent any, relation string, idsWithAttrs map[any]map[string]any) (*dbcontract.SyncResult, error)

SyncWithoutDetachingRelationWithPivot is SyncRelationWithPivot minus the detach step.

func (*Query) Table

func (r *Query) Table(name any, args ...any) contractsorm.Query

Table points the query at a table by name. A string name is stored bare and the framework grammar applies the connection prefix once when the statement is rendered; a querybuilder.Expression is stored as given and rendered verbatim, for a caller naming a table that is already qualified.

func (*Query) ToRawSql

func (r *Query) ToRawSql() contractsorm.ToSql

func (*Query) ToSql

func (r *Query) ToSql() contractsorm.ToSql

func (*Query) ToggleRelation

func (r *Query) ToggleRelation(parent any, relation string, ids []any) (*dbcontract.SyncResult, error)

ToggleRelation attaches missing entries and detaches existing ones.

func (*Query) ToggleRelationWithPivot

func (r *Query) ToggleRelationWithPivot(parent any, relation string, idsWithAttrs map[any]map[string]any) (*dbcontract.SyncResult, error)

ToggleRelationWithPivot is ToggleRelation with per-ID pivot column values for newly attached rows.

func (*Query) Touch

func (r *Query) Touch(column ...string) (*contractsdb.Result, error)

Touch sets the model's updated-at column, or the named column, to now on every matching row. Mirrors Builder::touch: a model without an updated-at column touches nothing and reports it.

func (*Query) Update

func (r *Query) Update(column any, value ...any) (*contractsdb.Result, error)

func (*Query) UpdateExistingPivotRelation

func (r *Query) UpdateExistingPivotRelation(parent any, relation string, id any, attrs map[string]any) (int64, error)

UpdateExistingPivotRelation updates pivot columns for an already-attached id. When pivotTimestamps is enabled and attrs doesn't already set updated_at, injects time.Now() into the update map. No-op (returns 0) if no matching pivot row exists.

func (*Query) UpdateOrCreate

func (r *Query) UpdateOrCreate(dest any, attributes any, values any) error

UpdateOrCreate looks a model up, writing the values it was given either way: the found model is saved with them, and a model that was not found is created carrying them.

func (*Query) UpdateOrCreateRelation

func (r *Query) UpdateOrCreateRelation(parent any, relation string, attrs map[string]any, values map[string]any, dest any) error

UpdateOrCreateRelation finds the first related row matching attrs (or creates one), then overlays values onto it and persists. Always saves dest.

func (*Query) Upsert

func (r *Query) Upsert(values any, uniqueBy []string, update ...any) (*contractsdb.Result, error)

Upsert inserts the rows, updating the listed columns of a row whose uniqueBy columns already exist. Mirrors Builder::upsert on a model: timestamps are added to every row, the created-at column is never in the update list, and the updated-at column always is.

func (*Query) UseWritePdo

func (r *Query) UseWritePdo() contractsorm.Query

UseWritePdo forces the query's reads to resolve to the write connection instead of the replica, so a read that must observe a write issued on the same connection is not served by a lagging replica. It mirrors Laravel's Builder::useWritePdo(), which stores the flag the connection call reads as the inverse of its $useReadPdo argument; in this port the executor's readPool honours it.

func (*Query) Value

func (r *Query) Value(column string, dest any) error

Value retrieves one column of the first row. Mirrors Builder::value, which is first([$column]) read back by the column's bare name.

func (*Query) When

func (r *Query) When(condition bool, callback func(query contractsorm.Query) contractsorm.Query, falseCallback ...func(query contractsorm.Query) contractsorm.Query) contractsorm.Query

func (*Query) Where

func (r *Query) Where(query any, args ...any) contractsorm.Query

func (*Query) WhereAll

func (r *Query) WhereAll(columns []string, args ...any) contractsorm.Query

func (*Query) WhereAny

func (r *Query) WhereAny(columns []string, args ...any) contractsorm.Query

func (*Query) WhereBelongsTo

func (r *Query) WhereBelongsTo(related any, relation ...string) contractsorm.Query

WhereBelongsTo constrains the query to the rows that belong to the given model or models. Mirrors whereBelongsTo: the parent's foreign key is matched against the related models' keys, and the relation defaults to the related model's type name.

func (*Query) WhereBetween

func (r *Query) WhereBetween(column string, x, y any) contractsorm.Query

func (*Query) WhereDoesntHave

func (r *Query) WhereDoesntHave(relation string, args ...any) contractsorm.Query

WhereDoesntHave adds a relationship absence condition to the query with where clauses.

func (*Query) WhereDoesntHaveMorph

func (r *Query) WhereDoesntHaveMorph(relation string, types []any, args ...any) contractsorm.Query

WhereDoesntHaveMorph adds a polymorphic absence condition with where clauses.

func (*Query) WhereDoesntHaveRelation

func (r *Query) WhereDoesntHaveRelation(relation string, column any, args ...any) contractsorm.Query

WhereDoesntHaveRelation adds an absence condition with a single where on the related rows. Mirrors whereDoesntHaveRelation.

func (*Query) WhereHas

func (r *Query) WhereHas(relation string, args ...any) contractsorm.Query

WhereHas adds a relationship count / exists condition to the query with where clauses. Functionally identical to Has - the rename merely makes call sites that always pass a callback read more naturally.

func (*Query) WhereHasMorph

func (r *Query) WhereHasMorph(relation string, types []any, args ...any) contractsorm.Query

WhereHasMorph adds a polymorphic existence condition with where clauses; callbacks may be MorphRelationCallback for per-type scoping.

func (*Query) WhereIn

func (r *Query) WhereIn(column string, values []any) contractsorm.Query

WhereIn adds a "where column in (...)" clause. The column and the value list are added as one condition carrying a slice argument, not as a raw "IN ?" fragment: the compiler reads a slice argument as the IN list and expands it to one placeholder per value (Laravel binds whereIn the same way). A raw fragment would bind the whole slice to a single placeholder.

func (*Query) WhereJsonContains

func (r *Query) WhereJsonContains(column string, value any) contractsorm.Query

func (*Query) WhereJsonContainsKey

func (r *Query) WhereJsonContainsKey(column string) contractsorm.Query

func (*Query) WhereJsonDoesntContain

func (r *Query) WhereJsonDoesntContain(column string, value any) contractsorm.Query

func (*Query) WhereJsonDoesntContainKey

func (r *Query) WhereJsonDoesntContainKey(column string) contractsorm.Query

func (*Query) WhereJsonLength

func (r *Query) WhereJsonLength(column string, args ...any) contractsorm.Query

func (*Query) WhereKey

func (r *Query) WhereKey(id any) contractsorm.Query

WhereKey constrains the query to the row(s) with the given primary key. Mirrors Builder::whereKey: a model stands for its own key, a slice for several keys, and the column is qualified by the model's table so a joined statement still compares the model's own id.

func (*Query) WhereKeyNot

func (r *Query) WhereKeyNot(id any) contractsorm.Query

WhereKeyNot excludes the row(s) with the given primary key. Mirrors Builder::whereKeyNot.

func (*Query) WhereNone

func (r *Query) WhereNone(columns []string, args ...any) contractsorm.Query

func (*Query) WhereNotBetween

func (r *Query) WhereNotBetween(column string, x, y any) contractsorm.Query

func (*Query) WhereNotIn

func (r *Query) WhereNotIn(column string, values []any) contractsorm.Query

func (*Query) WhereNotNull

func (r *Query) WhereNotNull(column string) contractsorm.Query

func (*Query) WhereNull

func (r *Query) WhereNull(column string) contractsorm.Query

func (*Query) WhereRelation

func (r *Query) WhereRelation(relation string, column any, args ...any) contractsorm.Query

WhereRelation adds an existence condition with a single where on the related rows. Mirrors whereRelation: the column may instead be a callback that constrains the related rows freely.

func (*Query) With

func (r *Query) With(args ...any) contractsorm.Query

With eagerly loads the given relationships using Goravel's own loader. Accepts the union of fedaco's with(...) shapes; see the orm.Query interface comment for the full grammar.

func (*Query) WithAggregate

func (r *Query) WithAggregate(relation, column, fn string, args ...any) contractsorm.Query

WithAggregate adds a sub-select to include an aggregate value for a relationship. fn must be one of: count, max, min, sum, avg, exists.

func (*Query) WithAttributes

func (r *Query) WithAttributes(attributes any, args ...any) contractsorm.Query

WithAttributes records attributes for every model the query creates and, unless asConditions is false, adds each as a where equality. Mirrors Builder::withAttributes. The attributes may be a map or a single column followed by its value; a trailing bool is asConditions.

func (*Query) WithAvg

func (r *Query) WithAvg(relation, column string, args ...any) contractsorm.Query

WithAvg adds sub-select queries to include the average of the relation's column.

func (*Query) WithContext

func (r *Query) WithContext(ctx context.Context) contractsorm.Query

func (*Query) WithCount

func (r *Query) WithCount(relations ...any) contractsorm.Query

WithCount adds sub-select queries to count the relations. Each entry may be either:

  • a string ("Books") - emits `(SELECT COUNT(*) FROM ...) AS books_count`
  • a contractsorm.RelationCount struct for scoped counts and/or custom alias

func (*Query) WithExists

func (r *Query) WithExists(relations ...string) contractsorm.Query

WithExists adds sub-select queries to include the existence of related models. The result is emitted as `CASE WHEN EXISTS (...) THEN 1 ELSE 0 END` for cross-dialect portability (SQL Server has no boolean literal). The dest field may be either `bool` or an integer type - Go's database/sql layer converts 0/1 ints to bool automatically.

func (*Query) WithMax

func (r *Query) WithMax(relation, column string, args ...any) contractsorm.Query

WithMax adds sub-select queries to include the max of the relation's column.

func (*Query) WithMin

func (r *Query) WithMin(relation, column string, args ...any) contractsorm.Query

WithMin adds sub-select queries to include the min of the relation's column.

func (*Query) WithOnly

func (r *Query) WithOnly(args ...any) contractsorm.Query

WithOnly clears the eager-load list, then adds the given relations. Mirrors fedaco's withOnly(). Useful when a default-scoped query has eager loads you want to override.

func (*Query) WithSum

func (r *Query) WithSum(relation, column string, args ...any) contractsorm.Query

WithSum adds sub-select queries to include the sum of the relation's column.

func (*Query) WithTrashed

func (r *Query) WithTrashed() contractsorm.Query

func (*Query) WithWhereHas

func (r *Query) WithWhereHas(relation string, args ...any) contractsorm.Query

WithWhereHas constrains the query by the relation and eager loads the relation under the same constraint. Mirrors withWhereHas: the relation may carry a column list ("Books:id,title"), which applies to the eager load alone, as Str::before($relation, ':') strips it from the whereHas.

func (*Query) Without

func (r *Query) Without(relations ...string) contractsorm.Query

Without removes the named relations from the eager-load list. Mirrors fedaco's without(). Names must match exactly (including dot-paths, e.g. "Books.Author").

func (*Query) WithoutEvents

func (r *Query) WithoutEvents() contractsorm.Query

func (*Query) WithoutGlobalScopes

func (r *Query) WithoutGlobalScopes(names ...string) contractsorm.Query

type Row

type Row struct {
	// contains filtered or unexported fields
}

func (*Row) Err

func (r *Row) Err() error

func (*Row) Scan

func (r *Row) Scan(value any) error

type Select

type Select struct {
	// contains filtered or unexported fields
}

type Table

type Table struct {
	// contains filtered or unexported fields
}

type ToSql

type ToSql struct {
	// contains filtered or unexported fields
}

ToSql reports the statement a query would run, without running it.

GORM used to report these by running its own builder in a dry-run session, so what a caller saw was GORM's idea of the statement. They are compiled here instead, through the same path the ORM executes, so the reported statement is the one that would actually run — dialect placeholders and all.

func NewToSql

func NewToSql(query *Query, log log.Log, raw bool) *ToSql

func (*ToSql) Count

func (r *ToSql) Count() string

func (*ToSql) Create

func (r *ToSql) Create(value any) string

func (*ToSql) Delete

func (r *ToSql) Delete(dests ...any) string

func (*ToSql) Find

func (r *ToSql) Find(dest any, conds ...any) string

func (*ToSql) First

func (r *ToSql) First(dest any) string

func (*ToSql) ForceDelete

func (r *ToSql) ForceDelete(dests ...any) string

func (*ToSql) Get

func (r *ToSql) Get(dest any) string

Get looks a model up, which is the same statement Find reports without conditions.

func (*ToSql) Pluck

func (r *ToSql) Pluck(column string, dest any) string

func (*ToSql) Save

func (r *ToSql) Save(dest any) string

func (*ToSql) Sum

func (r *ToSql) Sum(column string, dest any) string

func (*ToSql) Update

func (r *ToSql) Update(column any, value ...any) string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL