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

gorm

package
v1.20.0-alpha.2 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 42 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 — from, select, where, join, group, having, order, limit, offset, distinct and lock — live on the OrmBuilder's persistent builder (OrmBuilder.query, read back through its State()), the way Laravel keeps them on Query\Builder. Conditions deliberately has no second copy of them: the table a query names (Table) and the conditions the ORM records internally (Find's inline conditions, the FirstOr* fold, the pivot chain) are written straight onto that builder when they are called.

What remains falls into three groups:

  • ORM state: the model and destination, the eager loads, the queued global scopes, the write-path filters (omit, pendingAttributes) and switches (useWritePdo, withoutEvents, withoutGlobalScopes, withoutTimestamps, withoutTouch, withTrashed, onlyTrashed), and the error a rejected condition carries;
  • deferred, model-dependent clauses: selectSubs (WithCount and the like) and relations (the relationship existence conditions), rendered at compile time when the parent model is known;
  • relation shaping: oneOfMany, throughRead and pivotRead, which rewrite a relation read.

raw is the one SQL-level member kept on purpose: a caller-supplied whole statement (Raw) has no home on the query builder, whose State models clauses the grammar compiles rather than a finished statement — Laravel has no such builder member either (fromQuery runs the statement on the connection). compileSelect and compileChunkSelect return it verbatim, and the mass-update / delete guard counts it as a constraint, so it stays here as a Select.

type Event

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

func NewEvent

func NewEvent(query *OrmBuilder, 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 OrmBuilder

type OrmBuilder 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) (*OrmBuilder, contractsdatabase.Config, error)

func NewOrmBuilder

func NewOrmBuilder(
	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,
) *OrmBuilder

func (*OrmBuilder) AssociateRelation

func (r *OrmBuilder) 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. A nil owner clears the foreign key (and the morph type) instead of erroring — Laravel's associate(null); a non-nil owner must be a pointer to a struct.

RelationWriter.Associate shell (contracts/database/orm/relation_writer.go:122) — reached through Query.Relation(parent, name); the flat Orm.Associate form intentionally does not exist (relation_writer.go:9).

func (*OrmBuilder) AttachRelation

func (r *OrmBuilder) 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.

RelationWriter.Attach shell (contracts/database/orm/relation_writer.go:134) — reached through Query.Relation(parent, name); the flat Orm.Attach form intentionally does not exist (relation_writer.go:9).

func (*OrmBuilder) AttachRelationOrFail

func (r *OrmBuilder) AttachRelationOrFail(parent any, relation string, ids []any) error

AttachRelationOrFail is AttachRelation inside a transaction — InteractsWithPivotTable::attachOrFail (InteractsWithPivotTable.php:365).

func (*OrmBuilder) AttachWithPivotRelation

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

AttachWithPivotRelation is Attach with per-row pivot column values.

func (*OrmBuilder) Avg

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

func (*OrmBuilder) Begin

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

DEPRECATED Use BeginTransaction instead.

func (*OrmBuilder) BeginTransaction

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

func (*OrmBuilder) Chunk

func (r *OrmBuilder) Chunk(size uint64, dest any, callback func(page int) error) error

Chunk reads the query in offset pages of size rows, mirroring Eloquent's BuildsQueries::chunk: the query is given the model's qualified key ascending order when it carries none (Eloquent's Builder::enforceOrderBy override; the raw query builder would refuse instead), the caller's offset and limit are honoured as the starting point and the ceiling, every page is scanned into dest — a non-nil pointer to a slice of models — and callback runs with the 1-based page number after the page's model events, where a callback returning errors.DatabaseChunkStopped stops the walk cleanly (Laravel's `return false`). The loop continues only while a full page came back.

func (*OrmBuilder) ChunkById

func (r *OrmBuilder) ChunkById(size uint64, dest any, callback func(page int) error, column ...string) error

ChunkById chunks by comparing ids, mirroring BuildsQueries::chunkById: each page is fetched with ForPageAfterId — the caller's offset applies to the first page only, the caller's limit caps every page size, and a zero-size chunk breaks before any query is issued — and the alias value of the page's last row drives the next page's keyset predicate. The column and alias default the way the relation overrides resolve them: a many-to-many read walks the related key qualified by its table, a through read the related model's qualified key, anything else the model's bare key name (Eloquent's Builder::defaultKeyName); column may be (column) or (column, alias).

func (*OrmBuilder) ChunkByIdDesc

func (r *OrmBuilder) ChunkByIdDesc(size uint64, dest any, callback func(page int) error, column ...string) error

ChunkByIdDesc is ChunkById in descending order, mirroring BuildsQueries::chunkByIdDesc: each page is fetched with ForPageBeforeId.

func (*OrmBuilder) Clone

func (r *OrmBuilder) 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 (*OrmBuilder) ColumnType

func (r *OrmBuilder) ColumnType(model any, column string) (reflect.Type, bool, error)

ColumnType reports the Go type of model's column — W3, the schemaField.FieldType the dissociate writers zero and castKeys targets; false when the schema carries no such column.

func (*OrmBuilder) ColumnValue

func (r *OrmBuilder) ColumnValue(model any, column string) (any, error)

ColumnValue reads the value of a DB column off a model through the parsed schema — W2, the promoted Hooks.ReadColumn; it is readParentColumn, error text included.

func (*OrmBuilder) Commit

func (r *OrmBuilder) Commit() error

func (*OrmBuilder) ConfigurePivotRead

func (r *OrmBuilder) ConfigurePivotRead(accessor string, columns []string) contractsorm.Query

ConfigurePivotRead applies the relation object's call-time pivot-read state to this builder — the Go form of Eloquent's withPivot()/as() mutating BelongsToMany::$pivotColumns and BelongsToMany::$accessor at call time: state aliasedPivotColumns (:970-983) consumes when get() installs shouldSelect and hydratePivotRelation (:1234-1242) consumes after the read. accessor re-points the hydration field name ("" keeps the declaration's desc.pivotField); an accessor with no struct field by its name keeps the declared plan — the select list stays, the way Laravel's frozen alias list never changes, while hydration goes nowhere (Laravel sets the dynamic attribute a Go struct cannot carry). columns replaces the object's explicit pivot-column list — the render deduplicates it, the raw list stays on the object. The returned handle is this builder, or a guarded copy reporting the resolution error when accessor names a field the related model cannot hydrate into — the same OrmRelationPivotFieldNotStruct preparePivotHydration raises for a declaration-time typo (the leaf rebuilds onto the guarded handle, so the reads surface it). A builder carrying no many-to-many pivot read (a guarded handle, a non-m2m relation, a foreign driver) is returned unchanged.

func (*OrmBuilder) ConnectionIsCurrent

func (r *OrmBuilder) 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 (*OrmBuilder) Context

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

func (*OrmBuilder) Count

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

func (*OrmBuilder) Create

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

func (*OrmBuilder) CreateManyRelation

func (r *OrmBuilder) 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 (*OrmBuilder) CreateManyRelationQuietly

func (r *OrmBuilder) CreateManyRelationQuietly(parent any, relation string, dests any) error

CreateManyRelationQuietly is the slice form of CreateRelationQuietly — HasOneOrMany::createManyQuietly (HasOneOrMany.php:455): the whole slice creates inside one event-suppressed scope.

func (*OrmBuilder) CreateOrFirst

func (r *OrmBuilder) CreateOrFirst(dest any, conds ...any) error

CreateOrFirst creates the model from the given attributes (and values) without reading first, mirroring Eloquent's Builder::createOrFirst: the insert runs inside a savepoint when the query is bound to a transaction (withSavepointIfNeeded), and a unique-constraint violation is caught to read the existing row back over the write connection — where(attributes)->first() — before the error is rethrown as a typed violation.

func (*OrmBuilder) CreateOrFirstRelation

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

CreateOrFirstRelation attempts the insert immediately — with no lookup first, Laravel's createOrFirst contract — and, when the insert trips a unique constraint, reads the row attrs name back (over the write connection for the HasOneOrMany kinds, on the default connection for the through kinds) and returns it. For the BelongsToMany kinds the insert is the related row plus the pivot attach (BelongsToMany::create), the catch reads the related row back plainly and attaches it, and a second violation — or an already-attached pivot row — re-reads through the pivot-joined relation on the write connection, hydrating the Pivot struct. Supported kinds: HasOne, HasMany, MorphOne, MorphMany, HasOneThrough, HasManyThrough, Many2Many, MorphToMany.

RelationWriter.CreateOrFirst shell (contracts/database/orm/relation_writer.go:108) — reached through Query.Relation(parent, name); the flat Orm.CreateOrFirst form intentionally does not exist (relation_writer.go:9).

func (*OrmBuilder) CreateRelation

func (r *OrmBuilder) 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. The created child is linked back to parent in memory under the relation's inverse name when one is in effect — HasOneOrMany::create applies applyInverseRelationToModel after the save (v12.55.1, HasOneOrMany.php:393; oracle: create.same-instance true). dest must be a non-nil pointer to a struct of the related type.

RelationWriter.Create shell (contracts/database/orm/relation_writer.go:53) — reached through Query.Relation(parent, name); the flat Orm.Create form intentionally does not exist (relation_writer.go:9).

func (*OrmBuilder) CreateRelationQuietly

func (r *OrmBuilder) CreateRelationQuietly(parent any, relation string, dest any) error

CreateRelationQuietly is CreateRelation without raising model events — Eloquent's HasOneOrMany::createQuietly (HasOneOrMany.php:403). The foreign key (and morph type) stamp and the insert are CreateRelation's; only the event dispatch is suppressed.

func (*OrmBuilder) Cursor

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

func (*OrmBuilder) CursorPaginate

func (r *OrmBuilder) 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 (*OrmBuilder) DB

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

func (*OrmBuilder) Decrement

func (r *OrmBuilder) 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 (*OrmBuilder) Delete

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

func (*OrmBuilder) DeleteRows

func (r *OrmBuilder) DeleteRows(table string, wheres []relations.RowWhere, scope contractsorm.PivotCallback) (int64, error)

DeleteRows compiles and runs a delete of the rows of table the predicates select — W6, the doDetach statement: execDelete over the scoped row query. Reports the rows affected.

func (*OrmBuilder) DetachRelation

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

DetachRelation removes pivot rows linking parent to the given ids. With nil ids, removes all pivot rows for parent (and morph type, for polymorphic); an explicitly empty (non-nil) id list is Laravel's detach([]) no-op — 0, no statement. Returns the number of rows removed.

func (*OrmBuilder) DetachRelationOrFail

func (r *OrmBuilder) DetachRelationOrFail(parent any, relation string, ids []any) (int64, error)

DetachRelationOrFail is DetachRelation inside a transaction — InteractsWithPivotTable::detachOrFail (:562).

func (*OrmBuilder) DissociateRelation

func (r *OrmBuilder) 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 (*OrmBuilder) Distinct

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

func (*OrmBuilder) DoesntHave

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

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

func (*OrmBuilder) DoesntHaveMorph

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

DoesntHaveMorph adds a polymorphic relationship absence condition.

func (*OrmBuilder) Driver

func (r *OrmBuilder) Driver() string

func (*OrmBuilder) Each

func (r *OrmBuilder) Each(dest any, callback func(index int) error) error

Each executes callback over every matching model one at a time, reading 1000 rows per statement and walking offset pages — the walk BuildsQueries::each, a chunk(1000) wrapper, performs. dest is a non-nil pointer to a model and holds the current row when the callback runs; index is the model's key within its page, the key Laravel hands each()'s callback.

func (*OrmBuilder) EachById

func (r *OrmBuilder) EachById(size uint64, dest any, callback func(index int) error, column ...string) error

EachById executes callback over every matching model one at a time, walking the keyset like BuildsQueries::eachById. dest holds the current row and index is the model's 0-based ordinal across the whole iteration — Laravel's ((page-1)*size + key) arithmetic.

func (*OrmBuilder) Except

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

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

func (*OrmBuilder) Exec

func (r *OrmBuilder) 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 (*OrmBuilder) Exists

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

func (*OrmBuilder) Find

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

func (*OrmBuilder) FindMany

func (r *OrmBuilder) 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 (*OrmBuilder) FindOr

func (r *OrmBuilder) 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.

When id is a slice of primary keys and dest points to a slice, the read is findMany's whereKey IN read and the callback answers only a short result — the semantics Laravel gives a relation's findOr (HasOneOrManyThrough::findOr): a complete key list returns the collection, a list with a missing id returns the callback's result, and an empty list returns the empty collection without calling the callback. The single-key form is unchanged: a missing key runs the callback.

func (*OrmBuilder) FindOrFail

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

FindOrFail retrieves the first row matching the given conditions, or, when the only condition is a slice of primary keys and dest points to a slice, every row whose key is in the list.

The key-list form mirrors the findOrFail Laravel gives a through relation (HasOneOrManyThrough::findOrFail): the ids run through findMany's whereKey IN read, and when the rows found fall short of the unique ids requested the error names the related model and every requested id — "No query results for model [Model] 1, 2", the message ModelNotFoundException carries — wrapping errors.OrmRecordNotFound so callers matching the sentinel keep working (oracle: findOrFail([1, 2]) with post 1 present prints "No query results for model [HasManyThroughTestPost] 1, 2" — the whole request, not the difference — and findOrFail([]) returns an empty collection). An empty list reads nothing and reports no error.

The single-condition form is unchanged: a miss reports the bare errors.OrmRecordNotFound.

func (*OrmBuilder) FindOrNewRelation

func (r *OrmBuilder) 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. For the BelongsToMany kinds the lookup is the pivot-joined relation read, a hit hydrates the Pivot struct, and a miss leaves dest as it was (no foreign key lands on the related row). dest must be a pointer to a struct.

func (*OrmBuilder) FirePivotEvent

func (r *OrmBuilder) FirePivotEvent(name string, pivot any) error

FirePivotEvent dispatches one model event on the pivot through the ORM's event machinery: the observer or DispatchesEvents handler registered for the pivot's type receives the event, and with none registered the call is the no-op Laravel's fireModelEvent is without a dispatcher. The PHP listener's `return false` cancel has no Go form: a handler reports failure by returning an error, which the caller propagates and the operation aborts on.

func (*OrmBuilder) First

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

func (*OrmBuilder) FirstFound

func (r *OrmBuilder) FirstFound(dest any) (bool, error)

FirstFound runs this query as a single-row read into dest and reports whether a row was found — firstRow, the flag firstFoundOn surfaces for the find-then-write family.

func (*OrmBuilder) FirstOr

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

func (*OrmBuilder) FirstOrCreate

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

func (*OrmBuilder) FirstOrCreateRelation

func (r *OrmBuilder) 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: the lookup runs first, and a miss routes through createOrFirst — the insert is attempted, and a unique-constraint violation reads the row the attributes name back instead of failing. For the BelongsToMany kinds the lookup is Laravel's two-level search — the pivot-joined relation read, then the plain related read whose hit is attached — before the createOrFirst fallback (firstOrCreateMany2Many, shared with UpdateOrCreateRelation).

func (*OrmBuilder) FirstOrFail

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

func (*OrmBuilder) FirstOrNew

func (r *OrmBuilder) 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, from the attributes and from the query's pending attributes (WithAttributes), the pending ones merging underneath the way newModelInstance() merges them, and nothing is written.

func (*OrmBuilder) FirstOrNewRelation

func (r *OrmBuilder) 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 (values win) and the pre-set FK (and morph type) — does NOT persist. Supported kinds: HasOne, HasMany, MorphOne, MorphMany, HasOneThrough, HasManyThrough (through kinds carry no key on the related row, so newInstance() alone is the whole response), Many2Many, MorphToMany (the search is the plain related read and the miss response is the attrs+values overlay; the pivot row is a later, explicit write).

func (*OrmBuilder) ForceDelete

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

func (*OrmBuilder) Fresh

func (r *OrmBuilder) Fresh(model any, dest any, with ...string) error

Fresh reads model's row back from the database into dest — a new instance — mirroring Eloquent's Model::fresh. dest is a non-nil pointer to the same model type; a model without a key (see freshKeys) or one the database no longer holds leaves dest zero-valued, Laravel's null. with names relations to eager-load on the fresh instance.

func (*OrmBuilder) Get

func (r *OrmBuilder) 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 the statement this call runs — on the scoped copy it reads from, never on the receiver — and they are installed only when that copy carried no selection, so a select the caller pre-set or a global scope wrote survives verbatim and a statement compiled afterwards is unchanged.

func (*OrmBuilder) GetCountForPagination

func (r *OrmBuilder) GetCountForPagination(columns ...string) (int64, error)

GetCountForPagination returns the count a paginator draws its page from, mirroring Laravel's Builder::getCountForPagination and the compiler the raw query carries for it (Builder::runPaginationCountQuery): the count statement is built on a clone — the query keeps its own clauses and bindings — and a grouped or having query is counted by wrapping its select in a derived table named "aggregate_table", so groups are counted, not rows. Count() keeps Laravel's count() semantics — a single aggregate over the grouped result — which is why the paginator reads its total here instead.

func (*OrmBuilder) Group

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

DEPRECATED Use GroupBy instead.

func (*OrmBuilder) GroupBy

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

func (*OrmBuilder) GroupLimit

func (r *OrmBuilder) GroupLimit(value int, column string) contractsorm.Query

GroupLimit sets the query builder's "group limit" — Query\Builder::groupLimit (Builder.php:3128), which the relation objects' limit() reaches through Eloquent\Builder::__call when the parent does not exist. The value and the partition column ride the persistent builder (newBuilder clones the whole state), so the select compiles through the grammar's group-limit dispatch — the row_number() over (partition by column) derived table bounded at value rows per group — in place of the plain select; a negative value is ignored, as groupLimit ignores it.

func (*OrmBuilder) Has

func (r *OrmBuilder) 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 (*OrmBuilder) HasMorph

func (r *OrmBuilder) 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. Pass []any{"*"} to resolve the values from the parent table instead — Laravel's hasMorph(['*']), whose types come from the distinct morph-type column read at compile time; Has / WhereHas / DoesntHave on a MorphTo take that path automatically, mirroring how Eloquent's has() delegates to hasMorph($relation, ['*']).

func (*OrmBuilder) Having

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

func (*OrmBuilder) Ident

func (r *OrmBuilder) Ident(parts ...string) string

Ident renders a dotted identifier with the connection's own quoting — ident.

func (*OrmBuilder) InRandomOrder

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

func (*OrmBuilder) InTransaction

func (r *OrmBuilder) InTransaction() bool

func (*OrmBuilder) Increment

func (r *OrmBuilder) 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 (*OrmBuilder) InsertRows

func (r *OrmBuilder) InsertRows(table string, rows []map[string]any) error

InsertRows inserts rows into table — W4, insertPivotRows verbatim.

func (*OrmBuilder) InverseRelationship

func (r *OrmBuilder) InverseRelationship() string

InverseRelationship reports the inverse relation name the after-query write-back links results to — "" when none is in effect (the relation was declared without an inverse, or WithoutInverseChaperone cleared it). The builder half of the relation object's GetInverseRelationship (contracts.QueryWithInverseChaperone).

func (*OrmBuilder) InverseWriteBackName

func (r *OrmBuilder) InverseWriteBackName(declared string) string

InverseWriteBackName reports the inverse relation name a relation write links the child back to — inverseWriteBackName: the live chaperone state when this builder carries one (installed at wrap time; WithoutChaperone / WithoutInverse clear it to ""), the declared name otherwise.

func (*OrmBuilder) IsIgnoringTouch

func (r *OrmBuilder) IsIgnoringTouch(model any) bool

IsIgnoringTouch reports whether a model's class ignores touches — database/orm's IsIgnoringTouch, read per call.

func (*OrmBuilder) IsUniqueConstraintViolation

func (r *OrmBuilder) IsUniqueConstraintViolation(err error) bool

IsUniqueConstraintViolation reports whether err is a unique-constraint violation the way each supported connection classifies one — isUniqueConstraintViolation.

func (*OrmBuilder) Join

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

Join adds an inner join. With condition arguments it is Laravel's structured Builder::join($table, $first, $operator, $second): the columns compare in an "on" clause and the corpus's join('posts', 'users.id', '=', 'posts.user_id') compiles as `inner join "posts" on "users"."id" = "posts"."user_id"` (oracle); a single callback argument builds a nested on-clause the way Laravel's Closure form does. Without arguments the string is taken as a whole clause — the "table on condition" fragment form the relation writers and the legacy callers use, handled by the inner builder's raw join — which has no Laravel join() form (Laravel writes it as joinRaw), so the fragment passes through as written instead of being bound as a value.

func (*OrmBuilder) Latest

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

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

func (*OrmBuilder) LatestOfMany

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

LatestOfMany is shorthand for ofMany with every column aggregated "MAX" — Laravel's latestOfMany($column), which defaults to "id". The related model's key is appended as MAX when the columns omit it.

func (*OrmBuilder) Lazy

func (r *OrmBuilder) Lazy(dest any, callback func(index int) error, chunkSize ...uint64) error

Lazy walks the query in pages of chunkSize (default 1000) and hands every hydrated model to callback one at a time through dest (a non-nil pointer to a model), with index counting the models seen so far, mirroring BuildsQueries::lazy: the query is given the model's qualified key ascending order when it carries none, a chunk size below 1 is refused (errors.QueryInvalidChunkSize), and the walk ends once a page comes back shorter than chunkSize. Go has no lazy collection, so the walk runs immediately and reports its error; the page sequence is the one Laravel's LazyCollection would pull.

func (*OrmBuilder) LazyById

func (r *OrmBuilder) LazyById(chunkSize uint64, dest any, callback func(index int) error, column ...string) error

LazyById is Lazy with chunkById's keyset, mirroring BuildsQueries::lazyById: each page is fetched with ForPageAfterId using the last model's id as the keyset, with the same column/alias defaults ChunkById resolves.

func (*OrmBuilder) LazyByIdDesc

func (r *OrmBuilder) LazyByIdDesc(chunkSize uint64, dest any, callback func(index int) error, column ...string) error

LazyByIdDesc is LazyById in descending order, mirroring BuildsQueries::lazyByIdDesc: each page is fetched with ForPageBeforeId.

func (*OrmBuilder) Limit

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

func (*OrmBuilder) Load

func (r *OrmBuilder) 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 (*OrmBuilder) LoadMissing

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

func (*OrmBuilder) LockForUpdate

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

func (*OrmBuilder) Make

func (r *OrmBuilder) Make(dest any, attributes ...any) error

Make builds an unsaved model instance carrying the query's pending attributes and the attributes it is given, mirroring Builder::make: newModelInstance() merges $pendingAttributes underneath the attributes it is given (array_merge($this->pendingAttributes, $attributes)), so an attribute passed here wins over a pending one. Nothing is written.

func (*OrmBuilder) MakeManyRelation

func (r *OrmBuilder) MakeManyRelation(parent any, relation string, records []map[string]any, dests any) error

MakeManyRelation is the slice form of MakeRelation: one unsaved instance per record, in record order, appended to dests — a pointer to a slice of structs (or pointers to structs).

func (*OrmBuilder) MakeRelation

func (r *OrmBuilder) MakeRelation(parent any, relation string, attrs map[string]any, dest any) error

MakeRelation returns an unsaved new instance of the related model carrying attrs with the parent key (and morph type) pre-set from parent — Laravel's HasOneOrMany::make, which never saves. The made child is linked back to parent in memory under the relation's inverse name when one is in effect (HasOneOrMany::make applies applyInverseRelationToModel, v12.55.1, HasOneOrMany.php:65; oracle: make.same-instance true). Supported kinds: HasOne, HasMany, MorphOne, MorphMany.

RelationWriter.Make shell (contracts/database/orm/relation_writer.go:65) — reached through Query.Relation(parent, name); the flat Orm.Make form intentionally does not exist (relation_writer.go:9).

func (*OrmBuilder) Max

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

func (*OrmBuilder) Min

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

func (*OrmBuilder) Model

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

func (*OrmBuilder) MorphAliasOf

func (r *OrmBuilder) MorphAliasOf(model any) (string, bool, error)

MorphAliasOf reports the morph alias a model registers through MorphClass() or the morph map, without the table-name fallback — resolveMorphAlias.

func (*OrmBuilder) NewPivotQuery

func (r *OrmBuilder) NewPivotQuery(table string, connection string) (contractsorm.Query, error)

NewPivotQuery builds the fresh builder AsPivot's newQueryWithoutRelationships() / newQueryWithoutScopes() / newModelQuery() hand the pivot: the pivot's own table on the pivot's connection. The builder's own connection — and "" — keeps this query, so its transaction, writer and grammar carry over; any other name resolves through the config exactly the way refreshConnection resolves a model's declared connection, cached on the queries map.

func (*OrmBuilder) NewQuery

func (r *OrmBuilder) NewQuery() contractsorm.Query

NewQuery builds the same query with no state of its own — fresh(). contracts Query.Fresh is the model refresh, hence the name.

func (*OrmBuilder) Observe

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

func (*OrmBuilder) OfMany

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

OfMany configures the relation to read one row per parent through the aggregate join Laravel's ofMany installs, mirroring its string form: the column's aggregate is taken per parent and the related model's key joins the aggregate set with the same aggregate, so ties resolve to the extreme key. Column and aggregate default to "id" / "MAX". Only MIN and MAX are accepted, case-insensitively, exactly as Laravel's ofMany requires; any other aggregate makes the relation query report errors.OrmRelationInvalidOfManyAggregate when it is compiled.

func (*OrmBuilder) OfManyColumns

func (r *OrmBuilder) OfManyColumns(columns ...contractsorm.OfManyColumn) contractsorm.Query

OfManyColumns configures the relation the way ofMany's ordered column map does, e.g. ofMany(['published_at' => 'max', 'id' => 'max']): the pairs are taken in order with each later pair breaking ties in the earlier ones, and the related model's key is appended with MAX when the columns omit it. Every pair's aggregate must be MIN or MAX, as Laravel's ofMany requires.

func (*OrmBuilder) Offset

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

func (*OrmBuilder) Oldest

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

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

func (*OrmBuilder) OldestOfMany

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

OldestOfMany is shorthand for ofMany with every column aggregated "MIN" — Laravel's oldestOfMany($column), which defaults to "id". The related model's key is appended as MAX when the columns omit it, exactly as ofMany appends it.

func (*OrmBuilder) Omit

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

func (*OrmBuilder) OnlyTrashed

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

func (*OrmBuilder) OrDoesntHave

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

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

func (*OrmBuilder) OrDoesntHaveMorph

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

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

func (*OrmBuilder) OrHas

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

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

func (*OrmBuilder) OrHasMorph

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

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

func (*OrmBuilder) OrWhere

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

OrWhere mirrors Eloquent's Builder::orWhere(), which is where() with the "or" connector.

func (*OrmBuilder) OrWhereAttachedTo

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

OrWhereAttachedTo is WhereAttachedTo with an "or" conjunction. Mirrors orWhereAttachedTo, which forwards to whereAttachedTo under Laravel's "or" boolean.

func (*OrmBuilder) OrWhereBelongsTo

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

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

func (*OrmBuilder) OrWhereBetween

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

func (*OrmBuilder) OrWhereColumn

func (r *OrmBuilder) OrWhereColumn(column1 string, column2 ...string) contractsorm.Query

OrWhereColumn compares two columns under the "or" connector, mirroring Builder::orWhereColumn.

func (*OrmBuilder) OrWhereDoesntHave

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

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

func (*OrmBuilder) OrWhereDoesntHaveMorph

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

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

func (*OrmBuilder) OrWhereDoesntHaveRelation

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

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

func (*OrmBuilder) OrWhereHas

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

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

func (*OrmBuilder) OrWhereHasMorph

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

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

func (*OrmBuilder) OrWhereIn

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

func (*OrmBuilder) OrWhereJsonContains

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

func (*OrmBuilder) OrWhereJsonContainsKey

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

func (*OrmBuilder) OrWhereJsonDoesntContain

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

func (*OrmBuilder) OrWhereJsonDoesntContainKey

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

func (*OrmBuilder) OrWhereJsonLength

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

func (*OrmBuilder) OrWhereNot

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

OrWhereNot mirrors Eloquent's Builder::orWhereNot (Builder.php:420): the same forms as WhereNot with the "or not" connector; the array form expands through addArrayOfWheres under the "or not" boolean, negating every column inside one group — `or not (not "b" = ? or not "c" = ?)`.

func (*OrmBuilder) OrWhereNotBetween

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

func (*OrmBuilder) OrWhereNotIn

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

func (*OrmBuilder) OrWhereNull

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

func (*OrmBuilder) OrWhereRaw

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

OrWhereRaw mirrors Eloquent's Builder::orWhereRaw.

func (*OrmBuilder) OrWhereRelation

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

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

func (*OrmBuilder) Order

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

DEPRECATED: Use OrderByRaw instead

func (*OrmBuilder) OrderBy

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

OrderBy adds an "order by" clause. The direction must be asc or desc, as Laravel requires; any other direction is an error (errors.QueryOrderDirectionInvalid). A custom direction such as "DESC NULLS LAST" goes through OrderByRaw, the only entry point that renders its argument verbatim, so no caller-supplied string reaches the SQL unvalidated.

func (*OrmBuilder) OrderByDesc

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

func (*OrmBuilder) OrderByRaw

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

func (*OrmBuilder) Paginate

func (r *OrmBuilder) 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). The count itself comes from GetCountForPagination, so a grouped query's total counts its groups.

func (*OrmBuilder) PivotTouchOwners

func (r *OrmBuilder) PivotTouchOwners(pivot any) error

PivotTouchOwners runs AsPivot::delete's touchOwners() call on the pivot through the ORM's own walk (touching.go touchOwners). A base pivot declares no touching relations, so — like Laravel's Model with its default $touches = [] — the walk resolves to nothing today, and a pivot shape that does declare relations is walked instead of skipped.

func (*OrmBuilder) Pluck

func (r *OrmBuilder) Pluck(column string, dest any, key ...string) error

Pluck retrieves a single column from the database, mirroring Laravel's pluck($column, $key): the select list becomes the plucked column — plus the key column when one is given — but only when the scoped query carries no selection, because Builder::pluck installs the pair through onceWithColumns, which writes the columns solely when they are null and restores them when the read completes: a select() the caller already wrote survives verbatim, and the installed pair lives only for this statement, so the query can still be executed afterwards (oracle, illuminate/database v12.55.1, executed against sqlite: select('name')->pluck('email') compiles `select "name" from "users"`; `$q->pluck('email'); $q->pluck('name')` compiles `select "email" from "users"` then `select "name" from "users"`). A queued selectSub — a WithCount / WithMax and the like — counts as an installed select list, because withAggregate wrote `from.*` and the subselect into the columns before pluck ran (oracle: withCount('posts')->pluck('email') compiles `select "users".*, (select count(*) ...) as "posts_count" from "users"`). The fold matches pluckFromArrayColumn, reading a row's columns by name, and a key equal to the column reuses the value (Laravel's onceWithColumns collapses that pair to a one-column select). dest receives the values, a pointer to a slice for the flat form or a pointer to a map keyed by the key column's values.

func (*OrmBuilder) PrimaryKey

func (r *OrmBuilder) PrimaryKey(model any) (string, bool, bool, error)

PrimaryKey reads model's primary key through the parsed schema — W10, the parseSchema(model).PrimaryFields[0] read FindOrNewRelation's found-check and touchIfTouching's WHERE anchor make: the first primary-key column, whether that field holds its Go zero (schemaField.ValueOf's flag) and whether the schema carries a primary key at all. The value is read off the struct the way readParentColumn addresses it (a pointer is dereferenced once).

func (*OrmBuilder) Raw

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

func (*OrmBuilder) ReadPivotParent

func (r *OrmBuilder) ReadPivotParent(parent any) (relations.PivotParentInfo, error)

ReadPivotParent projects the parent-model metadata AsPivot reads through its pivotParent link: the declared connection name AsPivot.php:57 stamps at construction, and the created-at / updated-at column names the timestamps checks and update stamping read (AsPivot.php:213,225,242).

The column names resolve from the parent's declared Go schema the way the touch machinery resolves them (touchedUpdatedAtColumn in touching.go): the automatic field's column, then the conventional created_at / updated_at column, else "" — the Go reading of PHP's null, which is what gates the pivot's timestamps flag. Laravel itself returns class constants here; the schema resolution is this ORM's documented timestamp convention, and a parent that declares no timestamp fields reports "".

func (*OrmBuilder) Refresh

func (r *OrmBuilder) Refresh(model any) error

Refresh re-reads model's row into model itself, mirroring Eloquent's Model::refresh: the same key-matched, scope-skipping read as Fresh, applied in place; a model without a key is returned unchanged and a row the database no longer holds reports errors.OrmModelNotFoundNoIds, firstOrFail's id-less message. Every relation the model carries loaded is re-loaded afterwards, refresh()'s reload of its relations. with names relations to eager-load when the row is found.

func (*OrmBuilder) Related

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

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

func (*OrmBuilder) Relation deprecated

func (r *OrmBuilder) 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.

Deprecated: use Related(parent, name) instead, Relation will be removed in a future major version. Related returns the relation builder object — contractsorm.RelationQuery and its per-kind write interfaces — the Go form of Laravel's relation classes.

func (*OrmBuilder) RelationInfoOf

func (r *OrmBuilder) RelationInfoOf(parent any, relation string) (relations.RelationInfo, error)

RelationInfoOf resolves parent's relation by name and projects it — the resolveRelation call every write shell opens with, projected through relationInfoFromDescriptor the way Wrap receives it. The projection is built without a bound read builder: OneOfMany and the MorphTo related-table fallback are read-path facts the write workers never consult.

func (*OrmBuilder) Restore

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

func (*OrmBuilder) Rollback

func (r *OrmBuilder) Rollback() error

func (*OrmBuilder) Save

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

func (*OrmBuilder) SaveManyRelation

func (r *OrmBuilder) 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 (*OrmBuilder) SaveManyRelationQuietly

func (r *OrmBuilder) SaveManyRelationQuietly(parent any, relation string, children any) error

SaveManyRelationQuietly is the slice form of SaveRelationQuietly — HasOneOrMany::saveManyQuietly (HasOneOrMany.php:373) and BelongsToMany::saveManyQuietly (BelongsToMany.php:1402): the whole slice saves inside one event-suppressed scope.

func (*OrmBuilder) SaveManyRelationWithPivot

func (r *OrmBuilder) 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 (*OrmBuilder) SaveQuietly

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

func (*OrmBuilder) SaveRelation

func (r *OrmBuilder) 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. The FK stamp also links child back to parent in memory under the relation's inverse name when one is in effect — the write-back SupportsInverseRelations::applyInverseRelationToModel applies (oracle: save.same-instance true). For BelongsToMany kinds (Many2Many, MorphToMany, MorphedByMany) persists child first, then writes a pivot row linking parent and child.

RelationWriter.Save shell (contracts/database/orm/relation_writer.go:32) — reached through Query.Relation(parent, name); the flat Orm.Save(parent, relation, child) form intentionally does not exist (relation_writer.go:9). 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 (*OrmBuilder) SaveRelationQuietly

func (r *OrmBuilder) SaveRelationQuietly(parent any, relation string, child any) error

SaveRelationQuietly is SaveRelation without raising model events — Eloquent's HasOneOrMany::saveQuietly (illuminate/database v12.55.1, HasOneOrMany.php:345, `Model::withoutEvents(fn () => $this->save($model))`) and BelongsToMany::saveQuietly (BelongsToMany.php:1366) on the relation object. The whole save runs on an event-suppressed session — the child's insert or update, the pivot attach and the owner touches are all quiet, the reach Eloquent's dispatcher swap has (Model::withoutEvents swaps the dispatcher for a NullDispatcher around the callback, HasEvents.php:445-460). Everything else is SaveRelation's.

func (*OrmBuilder) SaveRelationWithPivot

func (r *OrmBuilder) 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 (*OrmBuilder) Scan

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

func (*OrmBuilder) Scopes

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

Scopes applies one or more query scopes immediately, mirroring Eloquent's Builder::scopes(): the scopes run against this query at call time, not when a statement compiles, so a where chained after this call lands after the scope's clauses. Each scope's wheres are regrouped the way callScope groups them (applyScope). A return value whose concrete type is not an OrmBuilder is tolerated by keeping the receiver as the chain — the tolerance the deferred application always had.

func (*OrmBuilder) Select

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

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

func (*OrmBuilder) SelectRaw

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

func (*OrmBuilder) SelectRows

func (r *OrmBuilder) SelectRows(table string, columns []string, wheres []relations.RowWhere, scope contractsorm.PivotCallback) ([]map[string]any, error)

SelectRows reads columns of the rows of table the predicates select into column-keyed maps — W7, the existingPivotIDs / allPivotIDs read: the select list set on the fresh table query, the pivot scope replayed, then the predicates; findMapsCompiled is handed no scope, since the row query already carries it.

func (*OrmBuilder) SetColumn

func (r *OrmBuilder) SetColumn(model any, column string, value any) (bool, error)

SetColumn writes value into model's column through the parsed schema — W1, the schemaField.Set call the FK / attribute / touch writers make. The bool reports whether the schema carries the column; a model that is not a non-nil pointer to a struct cannot be written and reports OrmQueryInvalidModel (a nil model reports it from the schema parse).

func (*OrmBuilder) SetRelation

func (r *OrmBuilder) SetRelation(model any, relation string, value any) error

SetRelation stores value on model's relation field by name — the setRelationField call applyInverseRelationToCreated makes, with the same guards: model and value must both be non-nil pointers (model to a struct), any other shape is the no-op. value is passed as the pointer it is, which is what inverseParentRef yields for an addressable parent.

func (*OrmBuilder) SharedLock

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

func (*OrmBuilder) SimplePaginate

func (r *OrmBuilder) SimplePaginate(page, limit int, dest any) (bool, error)

SimplePaginate retrieves one page of rows without counting the total, mirroring Laravel's Builder::simplePaginate (Eloquent Builder.php:1143): a non-positive page and limit fall back to the same defaults as Paginate — page 1 and 15 rows — the query runs with one probe row (limit+1), dest receives at most limit rows, and the returned bool reports whether the probe row was present, which is Laravel's hasMorePages(). No count statement runs, so the page carries no total.

Oracle (v12.55.1, executed against sqlite; .claude/laravel-oracle/_simplepaginate_probe.php): a first page of 3 rows at perPage 2 runs `select * from "users" order by "id" asc limit 3 offset 0` as its only statement — paginate(2) runs a count first — trims its items to 2 and reports true; a last partial page runs `... limit 3 offset 2` and reports false; an exact page of 3 rows at perPage 3 runs `limit 4 offset 0` and reports false; a page beyond range runs `limit 3 offset 16` with 0 items and false; perPage 0 and null both fall back to 15 (`limit 16 offset 0`).

func (*OrmBuilder) Sole

func (r *OrmBuilder) 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 (*OrmBuilder) Sum

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

func (*OrmBuilder) SyncRelation

func (r *OrmBuilder) 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.

RelationWriter.Sync shell (contracts/database/orm/relation_writer.go:150) — reached through Query.Relation(parent, name); the flat Orm.Sync form intentionally does not exist (relation_writer.go:9).

func (*OrmBuilder) SyncRelationOrFail

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

SyncRelationOrFail is SyncRelation inside a transaction — InteractsWithPivotTable::syncOrFail (:157).

func (*OrmBuilder) SyncRelationWithPivot

func (r *OrmBuilder) 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 (*OrmBuilder) SyncRelationWithPivotValues

func (r *OrmBuilder) 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 (*OrmBuilder) SyncRelationWithPivotValuesOrFail

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

SyncRelationWithPivotValuesOrFail is SyncRelationWithPivotValues inside a transaction — InteractsWithPivotTable::syncWithPivotValuesOrFail (:200).

func (*OrmBuilder) SyncWithoutDetachingRelation

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

SyncWithoutDetachingRelation is SyncRelation minus the detach step.

func (*OrmBuilder) SyncWithoutDetachingRelationOrFail

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

SyncWithoutDetachingRelationOrFail is SyncWithoutDetachingRelation inside a transaction — InteractsWithPivotTable::syncWithoutDetachingOrFail (:170, `$this->syncOrFail($ids, false)`).

func (*OrmBuilder) SyncWithoutDetachingRelationWithPivot

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

SyncWithoutDetachingRelationWithPivot is SyncRelationWithPivot minus the detach step.

func (*OrmBuilder) Table

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

Table points the query at a table by name: the builder's from clause, the way Eloquent's Builder::from() sets it on the Query\Builder. 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. The trailing arguments are accepted for the contract's signature and take no part in the statement, as they never did.

func (*OrmBuilder) TableOf

func (r *OrmBuilder) TableOf(model any) (string, error)

TableOf resolves a model's declared table name without the connection prefix — tableNameFor.

func (*OrmBuilder) Take

func (r *OrmBuilder) Take(limit int) contractsorm.Query

Take is an alias for Limit, mirroring Eloquent\Builder::take — the builder-level alias, always the plain limit. The relation objects override both Take and Limit with Eloquent's relation-level limit (HasOneOrMany::limit HasOneOrMany.php:555, HasOneOrManyThrough::limit HasOneOrManyThrough.php:772 — database/gorm/relations has.go / through.go), which keeps this plain limit for an existing parent and routes a non-existing parent through GroupLimit (oracle /tmp/followup-take-grouplimit/take_grouplimit.php H1 / H7). BelongsToMany::take (BelongsToMany.php:1492) is still the promoted plain limit on the many-to-many object.

func (*OrmBuilder) ToRawSql

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

func (*OrmBuilder) ToSql

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

func (*OrmBuilder) ToggleRelation

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

ToggleRelation attaches missing entries and detaches existing ones.

func (*OrmBuilder) ToggleRelationOrFail

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

ToggleRelationOrFail is ToggleRelation inside a transaction — InteractsWithPivotTable::toggleOrFail (:75).

func (*OrmBuilder) ToggleRelationWithPivot

func (r *OrmBuilder) 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 (*OrmBuilder) Touch

func (r *OrmBuilder) 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.

On a query bound to a model — Model(m) — the touch also walks m's Touches owners once the row is stamped: Eloquent's Model::touch saves the model, so its save path runs touchOwners, while the unbound builder form only stamps, exactly as Builder::touch does.

func (*OrmBuilder) Update

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

func (*OrmBuilder) UpdateExistingPivotRelation

func (r *OrmBuilder) 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 (*OrmBuilder) UpdateExistingPivotRelationOrFail

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

UpdateExistingPivotRelationOrFail is UpdateExistingPivotRelation inside a transaction — InteractsWithPivotTable::updateExistingPivotOrFail (:299).

func (*OrmBuilder) UpdateOrCreate

func (r *OrmBuilder) 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. A create that loses a unique constraint race reads the winning row back (createOrFirst) and that row is filled with the values and saved too — Laravel's wasRecentlyCreated() branch.

func (*OrmBuilder) UpdateOrCreateRelation

func (r *OrmBuilder) 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. A miss creates through createOrFirst, and a row read back from a unique-constraint race is filled with the values and saved too — Laravel's wasRecentlyCreated() branch. Always saves dest on the found and race-read paths. For the BelongsToMany kinds the lookup is BelongsToMany::firstOrCreate's three-level search (firstOrCreateMany2Many): an attached hit comes back with its Pivot, an unattached hit is attached first, a miss is created and attached — and only that fresh insert skips the fill+save (BelongsToMany::updateOrCreate, BelongsToMany.php:707).

func (*OrmBuilder) UpdateRows

func (r *OrmBuilder) UpdateRows(table string, wheres []relations.RowWhere, scope contractsorm.PivotCallback, values map[string]any) (int64, error)

UpdateRows compiles and runs an update of values on the rows of table the predicates select — W5, the doUpdateExistingPivot / touchIfTouching statement: compileUpdate + execStatement over the scoped row query. Reports the rows affected.

func (*OrmBuilder) Upsert

func (r *OrmBuilder) 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 (*OrmBuilder) UpsertRelation

func (r *OrmBuilder) UpsertRelation(parent any, relation string, values []map[string]any, uniqueBy []string, update ...any) (*dbcontract.Result, error)

UpsertRelation merges the parent key (and the morph type, for MorphOne/MorphMany) into every row and delegates to the query-level upsert — the rows HasOneOrMany::upsert / MorphOneOrMany::upsert hand the query. Supported kinds: HasOne, HasMany, MorphOne, MorphMany.

RelationWriter.Upsert shell (contracts/database/orm/relation_writer.go:114) — reached through Query.Relation(parent, name); the flat Orm.Upsert form intentionally does not exist (relation_writer.go:9).

func (*OrmBuilder) UseLegacyGroupLimit

func (r *OrmBuilder) UseLegacyGroupLimit() bool

UseLegacyGroupLimit reports whether the bound grammar compiles the group limit through the legacy rewrite (MySqlGrammar::useLegacyGroupLimit — MySQL before 8.0.11, never MariaDB), the decision HasOneOrManyThrough::limit (:779-783) and BelongsToMany::limit (:1510-1514) consult before choosing the partition column. False when no grammar is bound.

func (*OrmBuilder) UseWritePdo

func (r *OrmBuilder) 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 (*OrmBuilder) UsesTimestamps

func (r *OrmBuilder) UsesTimestamps() bool

UsesTimestamps reports whether writes through the query stamp the model's automatic timestamps, the query-level form of Eloquent's HasTimestamps::usesTimestamps: false while a WithoutTimestamps scope is active, and false when the query's model carries the per-instance flag (a databaseorm.Timestamps whose Disabled field names it ignored). With no model attached only the scope is consulted.

func (*OrmBuilder) Value

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

Value retrieves one column of the first row, read back by the column's bare name. Mirrors Builder::value, which is first([$column]) — the scopes are applied before the onceWithColumns decision, exactly as in pluck() — so a selection the caller pre-set or a global scope wrote survives and the single column is installed only when the scoped query carries none (oracle pins in singleColumnFirstQuery).

func (*OrmBuilder) ValueOrFail

func (r *OrmBuilder) ValueOrFail(column string, dest any) error

ValueOrFail retrieves a single column of the first row into dest, mirroring Laravel's Builder::valueOrFail: the read Value makes, firstOrFail([$column]) read back by the column's bare name, except that a miss reports the model-not-found error naming the model instead of leaving dest untouched (oracle: the found read is `select "name" from "users" limit 1`; a miss over whereKey('bar') throws ModelNotFoundException "No query results for model [Model].").

func (*OrmBuilder) When

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

func (*OrmBuilder) Where

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

Where mirrors Eloquent's Builder::where() (Builder.php:352-365). A callback with no operator runs against a new query without relationships: its eager loads merge into this query and its wheres join this query as one nested group. Every other condition is handed to the inner database/query builder as written, which owns the operator and value grammar. Raw SQL has its own entry point in WhereRaw, the way Eloquent separates where() from whereRaw().

func (*OrmBuilder) WhereAll

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

WhereAll adds one condition per column, joined by "and" inside a single nested group; an IN or NOT IN against a slice expands to one WhereIn per column (Builder::whereAll).

func (*OrmBuilder) WhereAny

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

WhereAny adds one condition per column, joined by "or" inside a single nested group (Builder::whereAny).

func (*OrmBuilder) WhereAttachedTo

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

WhereAttachedTo constrains the query to the rows attached to the given model through a many-to-many relation. Mirrors whereAttachedTo($model, $relationshipName = null): the relation defaults to the plural camel form of the related model's type name and must resolve to a many-to-many relation.

func (*OrmBuilder) WhereAttachedToCollection

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

WhereAttachedToCollection is WhereAttachedTo for a collection of models, mirroring whereAttachedTo called with a collection: every model's key joins the list the existence subquery matches against the related table's key.

func (*OrmBuilder) WhereBelongsTo

func (r *OrmBuilder) 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 (*OrmBuilder) WhereBetween

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

WhereBetween mirrors Builder::whereBetween: the inner builder wraps the column and binds the two bounds in order.

func (*OrmBuilder) WhereColumn

func (r *OrmBuilder) WhereColumn(column1 string, column2 ...string) contractsorm.Query

WhereColumn compares two columns, mirroring Builder::whereColumn: one trailing column means equality, two mean the operator and then the column. The trailing arguments are normalised the way the raw query's WhereColumn normalises them.

func (*OrmBuilder) WhereDoesntHave

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

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

func (*OrmBuilder) WhereDoesntHaveMorph

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

WhereDoesntHaveMorph adds a polymorphic absence condition with where clauses.

func (*OrmBuilder) WhereDoesntHaveRelation

func (r *OrmBuilder) 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 (*OrmBuilder) WhereHas

func (r *OrmBuilder) 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 (*OrmBuilder) WhereHasMorph

func (r *OrmBuilder) 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 (*OrmBuilder) WhereIn

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

WhereIn adds a "where column in (...)" clause by calling the inner query builder's WhereIn, which expands the slice to one placeholder per value inside the wrapped column (Builder::whereIn). The raw "col in ?" fragments the pivot and Find conditions queue compile through the descriptor path.

func (*OrmBuilder) WhereJsonContains

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

WhereJsonContains calls the inner query builder's WhereJsonContains, which prepares the JSON value through the grammar before it is bound (Builder::whereJsonContains).

func (*OrmBuilder) WhereJsonContainsKey

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

WhereJsonContainsKey calls the inner query builder's WhereJsonContainsKey, which renders the dialect's key-existence check (Builder::whereJsonContainsKey).

func (*OrmBuilder) WhereJsonDoesntContain

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

WhereJsonDoesntContain is WhereJsonContains with the negation set (Builder::whereJsonDoesntContain).

func (*OrmBuilder) WhereJsonDoesntContainKey

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

WhereJsonDoesntContainKey is WhereJsonContainsKey with the negation set (Builder::whereJsonDoesntContainKey).

func (*OrmBuilder) WhereJsonLength

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

WhereJsonLength calls the inner query builder's JSON-length comparison (Builder::whereJsonLength); OrWhereJsonLength is the same comparison with the "or" connector.

func (*OrmBuilder) WhereKey

func (r *OrmBuilder) 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 (*OrmBuilder) WhereKeyNot

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

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

func (*OrmBuilder) WhereNone

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

WhereNone adds one condition per column, joined by "or" inside one negated group: the group carries the "not" connector, as Builder::whereNone runs whereAny with it.

func (*OrmBuilder) WhereNot

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

WhereNot mirrors Eloquent's Builder::whereNot (Builder.php:407), which is where($column, $operator, $value, $boolean.' not') — not the inner Query\Builder::whereNot. A callback with no other arguments runs as one nested group carrying the "and not" connector; a column with its value (or with no value) is handed to the inner builder's whereNot as written; an array first argument takes Eloquent's route into Query\Builder::where()'s is_array branch, which expands it through addArrayOfWheres under the "and not" boolean: every column entry is negated inside one nested group — `and not (not "b" = ? and not "c" = ?)` — where the raw builder's own whereNot nests twice (`and not (("b" = ? and "c" = ?))`).

func (*OrmBuilder) WhereNotBetween

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

func (*OrmBuilder) WhereNotIn

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

WhereNotIn mirrors Builder::whereNotIn: the same call with the negation set.

func (*OrmBuilder) WhereNotNull

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

func (*OrmBuilder) WhereNull

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

WhereNull mirrors Builder::whereNull; WhereNotNull and OrWhereNull are the same call with the negation and the connector changed.

func (*OrmBuilder) WhereRaw

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

WhereRaw mirrors Eloquent's Builder::whereRaw: the fragment renders verbatim and the values bind to its placeholders in order.

func (*OrmBuilder) WhereRelation

func (r *OrmBuilder) 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 (*OrmBuilder) With

func (r *OrmBuilder) 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 (*OrmBuilder) WithAggregate

func (r *OrmBuilder) WithAggregate(relation string, column any, 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. column is a column name, a table-qualified name, "*", or a raw expression (database/query's Raw / Expression) - the string|Expression union Laravel's withAggregate accepts. relation may carry an "as" rename ("foo as foo_bar"): the rename becomes the select alias verbatim, otherwise the alias is the Str::snake derivation Laravel computes from name, function and column.

func (*OrmBuilder) WithAttributes

func (r *OrmBuilder) 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 (*OrmBuilder) WithAvg

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

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

func (*OrmBuilder) WithContext

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

func (*OrmBuilder) WithCount

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

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

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

func (*OrmBuilder) WithExists

func (r *OrmBuilder) 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 (*OrmBuilder) WithMax

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

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

func (*OrmBuilder) WithMin

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

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

func (*OrmBuilder) WithOnly

func (r *OrmBuilder) 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 (*OrmBuilder) WithSavepoint

func (r *OrmBuilder) WithSavepoint(scope func() error) error

WithSavepoint runs scope directly outside a transaction and inside a savepoint within one — W8, withSavepointIfNeeded.

func (*OrmBuilder) WithSum

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

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

func (*OrmBuilder) WithTrashed

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

func (*OrmBuilder) WithWhereHas

func (r *OrmBuilder) 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 (*OrmBuilder) Without

func (r *OrmBuilder) 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 (*OrmBuilder) WithoutEvents

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

func (*OrmBuilder) WithoutGlobalScopes

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

WithoutGlobalScopes removes the named global scopes; called with no names it removes every scope.

Inherent Go limitation: a variadic call cannot distinguish no arguments from an empty slice, so WithoutGlobalScopes() and a call spreading an empty list behave alike here and remove all scopes. Laravel distinguishes them — withoutGlobalScopes() (null) removes all, while withoutGlobalScopes([]) removes none (oracle against illuminate/database v12.55.1: the empty array leaves every scope applied). The empty-slice shape is not expressible through this signature.

func (*OrmBuilder) WithoutInverseChaperone

func (r *OrmBuilder) WithoutInverseChaperone()

WithoutInverseChaperone clears the inverse write-back state — the builder half of the relation object's WithoutChaperone / WithoutInverse (SupportsInverseRelations::withoutChaperone, Concerns/SupportsInverseRelations.php:151). Cleared stays distinguishable from never installed: the sentinel keeps a non-nil state whose relation is "", so a write on this builder stops linking the created child (inverseWriteBackName, database/gorm/relation_writes.go) while a flat write on a declared inverse — no state installed — still does.

func (*OrmBuilder) WithoutTimestamps

func (r *OrmBuilder) WithoutTimestamps(callback func() error) error

WithoutTimestamps runs the callback with the query's automatic created_at / updated_at stamping suspended, mirroring Eloquent's HasTimestamps::withoutTimestamps: a write through the query while a scope is active leaves both columns alone — a value the caller supplied is still written — and the scope is re-entrant, each call restoring exactly its own suspension. The suspension is lifted before the callback's error propagates, the way Eloquent's try / finally restores its class list before an exception leaves the call.

Eloquent scopes the suspension to the model class because a PHP process keeps one static list per class; the Go scope suspends the one query instead, so the query and the copies it hands out (Clone, WithContext) suspend together, while a write through another query handle is not suspended.

func (*OrmBuilder) WriteSession

func (r *OrmBuilder) WriteSession() contractsorm.Query

WriteSession is the fresh session a relation write persists through, keeping the caller's event suppression — relationWriteSession().

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 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 *OrmBuilder, 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

Directories

Path Synopsis
Package relations hosts the relation builder objects Orm.Related / Query.Related return — the Go form of Eloquent's Relation classes as first-class query builders.
Package relations hosts the relation builder objects Orm.Related / Query.Related return — the Go form of Eloquent's Relation classes as first-class query builders.

Jump to

Keyboard shortcuts

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