Documentation
¶
Overview ¶
Package model reads and writes database rows as Go structs. A model is a plain struct with an ID field, and its table name defaults to the plural snake_case form of the type name (for example, BlogPost maps to blog_posts). Define a TableName() string method to use a different table name. Columns map to struct fields using the same rules as the db package.
type Post struct {
ID int64 `json:"id"`
Title string `json:"title"`
Votes int64 `json:"votes" db:",default"`
PublishedAt *time.Time `json:"published_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
posts, err := model.Query[Post]().Where("votes", ">", 100).Latest("published_at").Get(ctx)
post, err := model.Find[Post](ctx, r.PathValue("post"))
err = model.Create(ctx, &post)
err = model.Update(ctx, &post, db.Values{"title": form.Title})
Entry points such as Query, Find, Create, Update, and Delete run on the database carried by ctx, joining any open transaction started with db.Transaction. Call Builder.On to target a specific connection instead. Missing rows return *db.NotFoundError, which maps to HTTP 404.
Relationships ¶
Struct fields tagged with model:"belongs_to", "has_one", "has_many", or "belongs_to_many" represent relationships rather than table columns. Eager load them with Builder.With or Load:
type Post struct {
// ...
User *User `json:"user,omitzero" model:"belongs_to"`
Comments []Comment `json:"comments,omitzero" model:"has_many"`
}
posts, err := model.Query[Post]().With("user", "comments.user").Get(ctx)
A belongs_to_many relationship can also include columns from the join table by using a wrapper struct that embeds the related model alongside a struct field tagged model:"join":
type PostTag struct {
Tag
Join struct {
Pinned bool `json:"pinned"`
} `json:"join" model:"join"`
}
tags, err := model.Related[PostTag](&post, "tags").Where("post_tag.pinned", "=", true).Get(ctx)
Polymorphic relationships point to models of multiple types. A field tagged model:"morph_to" holds an interface implemented by those models and reads matching type and ID columns. Register polymorphic models in laravel.Options.Morphs. The inverse side uses morph_one or morph_many, and polymorphic many-to-many relationships use morph_to_many and morphed_by_many:
type Comment struct {
ID int64
CommentableType string
CommentableID int64
Commentable Commentable `model:"morph_to"`
}
Comments []Comment `model:"morph_many,name=commentable"`
The name option on a morph_one or morph_many field must match a morph_to relationship on the related model whose interface the parent implements, or using the relationship panics.
Relationship keys and join table names follow naming conventions (such as user_id for a belongs_to field named User). Override them with tag options after the relationship kind, such as model:"belongs_to,foreign_key=author_id":
- belongs_to: foreign_key, owner_key
- has_one and has_many: foreign_key, local_key
- belongs_to_many: table, parent_column, related_column
- morph_one and morph_many: name, local_key
- morph_to_many: name, table, related_column
- morphed_by_many: name, table, parent_column
A has_one_through or has_many_through field reaches distant models across intermediate relationships named by the through option, such as model:"has_many_through,through=environments.deployments".
Every relationship kind except morph_to accepts a scope option naming a method on the related model that constrains its query, such as model:"has_many,scope=Published" for func (Post) Published(*Builder[Post]) *Builder[Post]. A has_one, morph_one, or has_one_through field also accepts of_many (latest, oldest, max:column, or min:column), such as model:"has_one,of_many=latest", to select a single row from many.
Index ¶
- func Associate[T any](m *T, relation string, parent any)
- func Associated[T any](m *T, relation string) bool
- func Attach[T, K any](ctx context.Context, m *T, relation string, keys ...K) error
- func AttachWith[T any, K comparable](ctx context.Context, m *T, relation string, links map[K]db.Values) error
- func Create[T any](ctx context.Context, m *T) error
- func CreateMany[T any](ctx context.Context, models []T) error
- func CreateManyRelated[T, R any](ctx context.Context, m *T, relation string, related []R) error
- func CreateRelated[T, R any](ctx context.Context, m *T, relation string, related *R) error
- func Decrement[T any](ctx context.Context, m *T, column string, by int64) error
- func Delete[T any](ctx context.Context, m *T) error
- func Destroy[T any, K any](ctx context.Context, keys ...K) (int64, error)
- func Detach[T, K any](ctx context.Context, m *T, relation string, keys ...K) (int64, error)
- func Find[T any](ctx context.Context, key any) (T, error)
- func FindAll(ctx context.Context, t reflect.Type, keys []any) (reflect.Value, error)
- func FindMany[T any](ctx context.Context, keys any) ([]T, error)
- func FindMorph[I any](ctx context.Context, name string, key any) (I, error)
- func FirstOrCreate[T any](ctx context.Context, attributes, values db.Values) (m T, created bool, err error)
- func Fresh[T any](ctx context.Context, m *T) (T, error)
- func FromRoute[T any](r Request, param string) (T, error)
- func FromRouteBy[T any](r Request, param, column string) (T, error)
- func Increment[T any](ctx context.Context, m *T, column string, by int64) error
- func InsertMany[T any](ctx context.Context, models []T) error
- func Is[T any](a, b *T) bool
- func KeyField(t reflect.Type) (reflect.StructField, error)
- func Keys[T any](models []T) []any
- func Load[T any](ctx context.Context, m *T, relations ...string) error
- func LoadAvg[T any](ctx context.Context, m *T, relation, column string) error
- func LoadCount[T any](ctx context.Context, m *T, relations ...string) error
- func LoadExists[T any](ctx context.Context, m *T, relations ...string) error
- func LoadMany[T any](ctx context.Context, models []T, relations ...string) error
- func LoadManyMissing[T any](ctx context.Context, models []T, relations ...string) error
- func LoadManyQuery[T, R any](ctx context.Context, models []T, relation string, ...) error
- func LoadMax[T any](ctx context.Context, m *T, relation, column string) error
- func LoadMin[T any](ctx context.Context, m *T, relation, column string) error
- func LoadMissing[T any](ctx context.Context, m *T, relations ...string) error
- func LoadQuery[T, R any](ctx context.Context, m *T, relation string, ...) error
- func LoadSum[T any](ctx context.Context, m *T, relation, column string) error
- func MorphName[T any]() string
- func Refresh[T any](ctx context.Context, m *T) error
- func Relate[T, R any](m *T, relation string, related *R) error
- func Replicate[T any](m T) T
- func RouteKey(value any, column string) (any, error)
- func Save[T any](ctx context.Context, m *T) error
- func Update[T any](ctx context.Context, m *T, values db.Values) error
- func UpdateJoinRow[T, K any](ctx context.Context, m *T, relation string, key K, values db.Values) error
- func UpdateOrCreate[T any](ctx context.Context, attributes, values db.Values) (m T, created bool, err error)
- func Upsert[T any](ctx context.Context, models []T, unique []string, update ...string) (int64, error)
- func WithoutRelations(m reflect.Value) reflect.Value
- type Builder
- func (b *Builder[T]) Avg[V any](ctx context.Context, column string) (V, error)
- func (b *Builder[T]) Chunk(ctx context.Context, size int) iter.Seq2[[]T, error]
- func (b *Builder[T]) ChunkByID(ctx context.Context, size int) iter.Seq2[[]T, error]
- func (b *Builder[T]) ChunkByIDDesc(ctx context.Context, size int) iter.Seq2[[]T, error]
- func (b *Builder[T]) Count(ctx context.Context) (int, error)
- func (b *Builder[T]) CountDistinct(ctx context.Context, column string) (int, error)
- func (b *Builder[T]) CrossJoin(table string) *Builder[T]
- func (b *Builder[T]) Cursor(ctx context.Context) iter.Seq2[T, error]
- func (b *Builder[T]) CursorPaginate(ctx context.Context, page pagination.Page) (*pagination.CursorPaginator[T], error)
- func (b *Builder[T]) Decrement(ctx context.Context, column string, by int64) (int64, error)
- func (b *Builder[T]) Delete(ctx context.Context) (int64, error)
- func (b *Builder[T]) Distinct() *Builder[T]
- func (b *Builder[T]) DoesntHave(relation string) *Builder[T]
- func (b *Builder[T]) Exists(ctx context.Context) (bool, error)
- func (b *Builder[T]) Find(ctx context.Context, key any) (T, error)
- func (b *Builder[T]) FindMany(ctx context.Context, keys any) ([]T, error)
- func (b *Builder[T]) First(ctx context.Context) (T, error)
- func (b *Builder[T]) ForPage(page, perPage int) *Builder[T]
- func (b *Builder[T]) FromRoute(r Request, param string) (T, error)
- func (b *Builder[T]) FromRouteBy(r Request, param, column string) (T, error)
- func (b *Builder[T]) Get(ctx context.Context) ([]T, error)
- func (b *Builder[T]) GroupBy(columns ...string) *Builder[T]
- func (b *Builder[T]) Has(relation string) *Builder[T]
- func (b *Builder[T]) HasCount(relation, operator string, count int) *Builder[T]
- func (b *Builder[T]) Having(column, operator string, value any) *Builder[T]
- func (b *Builder[T]) HavingRaw(sql string, args ...any) *Builder[T]
- func (b *Builder[T]) InOrderOf(column string, values ...any) *Builder[T]
- func (b *Builder[T]) InRandomOrder() *Builder[T]
- func (b *Builder[T]) Increment(ctx context.Context, column string, by int64) (int64, error)
- func (b *Builder[T]) Join(table, first, operator, second string) *Builder[T]
- func (b *Builder[T]) JoinOn(table string, on func(q *db.Query) *db.Query) *Builder[T]
- func (b *Builder[T]) Latest(column string) *Builder[T]
- func (b *Builder[T]) LazyByID(ctx context.Context, size int) iter.Seq2[T, error]
- func (b *Builder[T]) LazyByIDDesc(ctx context.Context, size int) iter.Seq2[T, error]
- func (b *Builder[T]) LeftJoin(table, first, operator, second string) *Builder[T]
- func (b *Builder[T]) LeftJoinOn(table string, on func(q *db.Query) *db.Query) *Builder[T]
- func (b *Builder[T]) Limit(n int) *Builder[T]
- func (b *Builder[T]) LimitPer(column string) *Builder[T]
- func (b *Builder[T]) LockForUpdate() *Builder[T]
- func (b *Builder[T]) Max[V any](ctx context.Context, column string) (V, error)
- func (b *Builder[T]) Min[V any](ctx context.Context, column string) (V, error)
- func (b *Builder[T]) NoWait() *Builder[T]
- func (b *Builder[T]) Offset(n int) *Builder[T]
- func (b *Builder[T]) Oldest(column string) *Builder[T]
- func (b *Builder[T]) On(conn *db.DB) *Builder[T]
- func (b *Builder[T]) OrDoesntHave(relation string) *Builder[T]
- func (b *Builder[T]) OrHas(relation string) *Builder[T]
- func (b *Builder[T]) OrHaving(column, operator string, value any) *Builder[T]
- func (b *Builder[T]) OrWhere(column, operator string, value any) *Builder[T]
- func (b *Builder[T]) OrWhereBelongsTo(relation string, parent any) *Builder[T]
- func (b *Builder[T]) OrWhereDoesntHave[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
- func (b *Builder[T]) OrWhereDoesntHaveRelation(relation, column, operator string, value any) *Builder[T]
- func (b *Builder[T]) OrWhereDoesntHaveRelationEq(relation, column string, value any) *Builder[T]
- func (b *Builder[T]) OrWhereEq(column string, value any) *Builder[T]
- func (b *Builder[T]) OrWhereGe(column string, value any) *Builder[T]
- func (b *Builder[T]) OrWhereGroup(group func(*Builder[T]) *Builder[T]) *Builder[T]
- func (b *Builder[T]) OrWhereGt(column string, value any) *Builder[T]
- func (b *Builder[T]) OrWhereHas[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
- func (b *Builder[T]) OrWhereLe(column string, value any) *Builder[T]
- func (b *Builder[T]) OrWhereLike(column, pattern string, caseSensitive bool) *Builder[T]
- func (b *Builder[T]) OrWhereLt(column string, value any) *Builder[T]
- func (b *Builder[T]) OrWhereNe(column string, value any) *Builder[T]
- func (b *Builder[T]) OrWhereNotLike(column, pattern string, caseSensitive bool) *Builder[T]
- func (b *Builder[T]) OrWhereRaw(sql string, args ...any) *Builder[T]
- func (b *Builder[T]) OrWhereRelation(relation, column, operator string, value any) *Builder[T]
- func (b *Builder[T]) OrWhereRelationEq(relation, column string, value any) *Builder[T]
- func (b *Builder[T]) OrderBy(column string) *Builder[T]
- func (b *Builder[T]) OrderByCount(relation string) *Builder[T]
- func (b *Builder[T]) OrderByCountDesc(relation string) *Builder[T]
- func (b *Builder[T]) OrderByDesc(column string) *Builder[T]
- func (b *Builder[T]) OrderByDirection(column string, direction db.Direction) *Builder[T]
- func (b *Builder[T]) OrderByRaw(sql string, args ...any) *Builder[T]
- func (b *Builder[T]) OrderByRelevance(search db.FullText) *Builder[T]
- func (b *Builder[T]) OrderBySub(sub *db.Query) *Builder[T]
- func (b *Builder[T]) OrderBySubDesc(sub *db.Query) *Builder[T]
- func (b *Builder[T]) OrderByVectorDistance(column string, embedding db.Vector) *Builder[T]
- func (b *Builder[T]) Paginate(ctx context.Context, page pagination.Page) (*pagination.Paginator[T], error)
- func (b *Builder[T]) Pluck[V any](ctx context.Context, column string) ([]V, error)
- func (b *Builder[T]) Reorder() *Builder[T]
- func (b *Builder[T]) RightJoin(table, first, operator, second string) *Builder[T]
- func (b *Builder[T]) RightJoinOn(table string, on func(q *db.Query) *db.Query) *Builder[T]
- func (b *Builder[T]) Scope(scope func(*Builder[T]) *Builder[T]) *Builder[T]
- func (b *Builder[T]) Select(columns ...string) *db.Query
- func (b *Builder[T]) SharedLock() *Builder[T]
- func (b *Builder[T]) SimplePaginate(ctx context.Context, page pagination.Page) (*pagination.SimplePaginator[T], error)
- func (b *Builder[T]) SkipLocked() *Builder[T]
- func (b *Builder[T]) Sole(ctx context.Context) (T, error)
- func (b *Builder[T]) Sum[V any](ctx context.Context, column string) (V, error)
- func (b *Builder[T]) ToSQL(ctx context.Context) (string, []any, error)
- func (b *Builder[T]) Union(other *Builder[T]) *Builder[T]
- func (b *Builder[T]) UnionAll(other *Builder[T]) *Builder[T]
- func (b *Builder[T]) Update(ctx context.Context, values db.Values) (int64, error)
- func (b *Builder[T]) Value[V any](ctx context.Context, column string) (V, error)
- func (b *Builder[T]) When(condition bool, fn func(*Builder[T]) *Builder[T]) *Builder[T]
- func (b *Builder[T]) Where(column, operator string, value any) *Builder[T]
- func (b *Builder[T]) WhereAfterToday(column string) *Builder[T]
- func (b *Builder[T]) WhereBeforeToday(column string) *Builder[T]
- func (b *Builder[T]) WhereBelongsTo(relation string, parent any) *Builder[T]
- func (b *Builder[T]) WhereBetween(column string, low, high any) *Builder[T]
- func (b *Builder[T]) WhereColumn(first, operator, second string) *Builder[T]
- func (b *Builder[T]) WhereDate(column, operator string, value any) *Builder[T]
- func (b *Builder[T]) WhereDay(column, operator string, day int) *Builder[T]
- func (b *Builder[T]) WhereDistinctFrom(column string, value any) *Builder[T]
- func (b *Builder[T]) WhereDoesntHave[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
- func (b *Builder[T]) WhereDoesntHaveRelation(relation, column, operator string, value any) *Builder[T]
- func (b *Builder[T]) WhereDoesntHaveRelationEq(relation, column string, value any) *Builder[T]
- func (b *Builder[T]) WhereEq(column string, value any) *Builder[T]
- func (b *Builder[T]) WhereExists(sub *db.Query) *Builder[T]
- func (b *Builder[T]) WhereFullText(search db.FullText) *Builder[T]
- func (b *Builder[T]) WhereFuture(column string) *Builder[T]
- func (b *Builder[T]) WhereGe(column string, value any) *Builder[T]
- func (b *Builder[T]) WhereGroup(group func(*Builder[T]) *Builder[T]) *Builder[T]
- func (b *Builder[T]) WhereGt(column string, value any) *Builder[T]
- func (b *Builder[T]) WhereHas[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
- func (b *Builder[T]) WhereHasCount[R any](relation, operator string, count int, query func(*Builder[R]) *Builder[R]) *Builder[T]
- func (b *Builder[T]) WhereIn(column string, values any) *Builder[T]
- func (b *Builder[T]) WhereJSONContains(column string, value any) *Builder[T]
- func (b *Builder[T]) WhereJSONContainsKey(column string) *Builder[T]
- func (b *Builder[T]) WhereJSONDoesntContain(column string, value any) *Builder[T]
- func (b *Builder[T]) WhereJSONDoesntContainKey(column string) *Builder[T]
- func (b *Builder[T]) WhereJSONLength(column, operator string, length int) *Builder[T]
- func (b *Builder[T]) WhereLe(column string, value any) *Builder[T]
- func (b *Builder[T]) WhereLike(column, pattern string, caseSensitive bool) *Builder[T]
- func (b *Builder[T]) WhereLt(column string, value any) *Builder[T]
- func (b *Builder[T]) WhereMonth(column, operator string, month int) *Builder[T]
- func (b *Builder[T]) WhereNe(column string, value any) *Builder[T]
- func (b *Builder[T]) WhereNotDistinctFrom(column string, value any) *Builder[T]
- func (b *Builder[T]) WhereNotExists(sub *db.Query) *Builder[T]
- func (b *Builder[T]) WhereNotIn(column string, values any) *Builder[T]
- func (b *Builder[T]) WhereNotLike(column, pattern string, caseSensitive bool) *Builder[T]
- func (b *Builder[T]) WhereNotNull(column string) *Builder[T]
- func (b *Builder[T]) WhereNowOrFuture(column string) *Builder[T]
- func (b *Builder[T]) WhereNowOrPast(column string) *Builder[T]
- func (b *Builder[T]) WhereNull(column string) *Builder[T]
- func (b *Builder[T]) WherePast(column string) *Builder[T]
- func (b *Builder[T]) WhereRaw(sql string, args ...any) *Builder[T]
- func (b *Builder[T]) WhereRelation(relation, column, operator string, value any) *Builder[T]
- func (b *Builder[T]) WhereRelationEq(relation, column string, value any) *Builder[T]
- func (b *Builder[T]) WhereSub(sub *db.Query, operator string, value any) *Builder[T]
- func (b *Builder[T]) WhereTime(column, operator string, value any) *Builder[T]
- func (b *Builder[T]) WhereToday(column string) *Builder[T]
- func (b *Builder[T]) WhereTodayOrAfter(column string) *Builder[T]
- func (b *Builder[T]) WhereTodayOrBefore(column string) *Builder[T]
- func (b *Builder[T]) WhereVectorSimilarTo(column string, embedding db.Vector, minSimilarity float64) *Builder[T]
- func (b *Builder[T]) WhereYear(column, operator string, year int) *Builder[T]
- func (b *Builder[T]) With(relations ...string) *Builder[T]
- func (b *Builder[T]) WithAvg(relation, column string) *Builder[T]
- func (b *Builder[T]) WithCount(relations ...string) *Builder[T]
- func (b *Builder[T]) WithCountQuery[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
- func (b *Builder[T]) WithExists(relations ...string) *Builder[T]
- func (b *Builder[T]) WithMax(relation, column string) *Builder[T]
- func (b *Builder[T]) WithMin(relation, column string) *Builder[T]
- func (b *Builder[T]) WithQuery[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
- func (b *Builder[T]) WithSum(relation, column string) *Builder[T]
- type Change
- type Changes
- func Sync[T, K any](ctx context.Context, m *T, relation string, keys []K) (Changes[K], error)
- func SyncWith[T any, K comparable](ctx context.Context, m *T, relation string, links map[K]db.Values) (Changes[K], error)
- func Toggle[T, K any](ctx context.Context, m *T, relation string, keys []K) (Changes[K], error)
- type Created
- type CreatingHook
- type Deleted
- type DeletingHook
- type ExistsRule
- type Request
- type UniqueRule
- func (u UniqueRule[T]) Ignore(target any) UniqueRule[T]
- func (u UniqueRule[T]) IgnoreCase() UniqueRule[T]
- func (u UniqueRule[T]) Message(text string) UniqueRule[T]
- func (u UniqueRule[T]) Validate(ctx context.Context, f validation.Field) error
- func (u UniqueRule[T]) Where(column string, value any) UniqueRule[T]
- func (u UniqueRule[T]) WhereGroup(filter func(q *Builder[T]) *Builder[T]) UniqueRule[T]
- type Updated
- type UpdatingHook
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Associate ¶
Associate sets m's belongs_to or morph_to foreign key (and morph type for morph_to) from parent and stores a copy of parent in m's relationship field without writing to the database:
model.Associate(&post, "user", &user) err := model.Create(ctx, &post)
For a morph_to relationship, pass any model (value or pointer) whose pointer implements the relationship interface:
model.Associate(&comment, "commentable", &video)
Associate panics if relation is not a belongs_to or morph_to relationship on T, or if parent is not a matching model type.
func Associated ¶
Associated reports whether m's belongs_to or morph_to relationship currently has a non-zero, non-NULL foreign key value. Associated panics if relation is not a belongs_to or morph_to relationship on T.
func Attach ¶
Attach inserts join table rows linking m to the related records identified by keys (primary keys or persisted related models) on a belongs_to_many, morph_to_many, or morphed_by_many relationship:
err := model.Attach(ctx, &post, "tags", tag.ID) err := model.Attach(ctx, &post, "tags", tag)
Passing a key that is already attached inserts a duplicate row (or fails on a unique index). Use Sync to reconcile a full list, or AttachWith to set extra join table columns. If the relationship's join-row struct declares CreatedAt or UpdatedAt fields, Attach sets them automatically.
Attach returns an error if m (or a passed model) has a zero ID, and panics if relation is not a join-table relationship.
func AttachWith ¶
func AttachWith[T any, K comparable](ctx context.Context, m *T, relation string, links map[K]db.Values) error
AttachWith inserts join table rows like Attach while setting additional join table columns for each related key from links:
err := model.AttachWith(ctx, &user, "roles", map[int64]db.Values{
admin.ID: {"level": "owner", "expires_at": expires},
})
func Create ¶
Create inserts m into the database and populates its fields with the stored row, including the generated ID and any database defaults. If CreatedAt or UpdatedAt is zero, Create sets it to the current UTC time truncated to the connection's precision.
Every column is written, including zero values, except a zero ID and zero fields tagged db:",default", which let the database apply column defaults. PostgreSQL and SQLite return the stored row via RETURNING *; MySQL and MariaDB read it back by ID in a second query.
If *T implements CreatingHook, Creating runs inside a transaction with the insert. Create then dispatches a Created event.
func CreateMany ¶
CreateMany inserts each element of models using Create inside a single transaction and updates each element with the stored row:
posts := []models.Post{{Title: "One", UserID: user.ID}, {Title: "Two", UserID: user.ID}}
err := model.CreateMany(ctx, posts)
Each model runs its CreatingHook and queues a Created event until the transaction commits. If any insert fails, the transaction rolls back, no events are dispatched, and models is left unchanged.
func CreateManyRelated ¶
CreateManyRelated inserts every element of related through one of m's relationships in a single transaction, as described by CreateRelated. If any insert fails, the transaction rolls back and related is left unchanged:
tags := []models.Tag{{Name: "Go"}, {Name: "Laravel"}}
err := model.CreateManyRelated(ctx, &post, "tags", tags)
func CreateRelated ¶
CreateRelated inserts related through one of m's relationships, setting its foreign key (and morph type for polymorphic relationships) from m before inserting it with Create:
comment := models.Comment{UserID: user.ID, Body: form.Body}
err := model.CreateRelated(ctx, &post, "comments", &comment)
For a belongs_to_many or morph_to_many relationship, CreateRelated inserts both the related model and the join table row in one transaction:
tag := models.Tag{Name: "Go"}
err := model.CreateRelated(ctx, &post, "tags", &tag)
CreateRelated runs CreatingHook and dispatches Created for related. It returns an error if m has a zero ID, and panics if relation is belongs_to, morph_to, read-only, or does not hold type R.
func Decrement ¶
Decrement atomically subtracts by from column on m's database row and updates that field on m, as described by Increment.
func Delete ¶
Delete removes m's row from the database. If the row no longer exists, Delete returns *db.NotFoundError. If *T implements DeletingHook, Deleting runs inside a transaction with the delete. Delete then dispatches a Deleted event.
func Destroy ¶
Destroy loads and deletes the models whose primary keys are in keys inside a single transaction, returning the number of deleted rows:
deleted, err := model.Destroy[Post](ctx, form.PostIDs...)
Each matched model runs its DeletingHook and dispatches Deleted. Missing keys are skipped. To delete rows directly without running hooks or events, call Builder.Delete.
func Detach ¶
Detach deletes the join table rows linking m to keys (primary keys or persisted related models) and returns the number of rows removed. To detach every linked record, call Sync with an empty slice.
func Find ¶
Find returns the model of type T whose primary key equals key, as described by Builder.Find. If no row matches, Find returns *db.NotFoundError, which maps to HTTP 404:
post, err := model.Find[Post](r, r.PathValue("post"))
if err != nil {
return web.Fail(err)
}
func FindAll ¶
FindAll loads all rows of model type t whose primary keys are in keys from ctx's database connection without eager-loading relationships, returning a reflect.Value holding []t in database order and skipping missing keys.
func FindMany ¶
FindMany returns the models of type T whose primary keys match keys, as described by Builder.FindMany.
func FindMorph ¶
FindMorph resolves a polymorphic model by its morph type name and primary key, returning it as the morph_to interface type I:
owner, err := model.FindMorph[models.Imageable](ctx, form.ImageableType, form.ImageableID)
FindMorph looks up models registered in laravel.Options.Morphs whose pointer implements I. String keys are parsed into the matched model's ID type like Builder.Find. If no registered model matches name or no row matches key, FindMorph returns *db.NotFoundError. FindMorph panics if I is not an interface or if no registered models implement I.
func FirstOrCreate ¶
func FirstOrCreate[T any](ctx context.Context, attributes, values db.Values) (m T, created bool, err error)
FirstOrCreate returns the first model matching attributes, or inserts a new model combining attributes and values if none exists, dispatching Created. The created return value reports whether a new row was inserted:
user, created, err := model.FirstOrCreate[User](ctx, db.Values{"email": email}, db.Values{"name": name})
Add a unique index on the attributes columns so concurrent calls race safely: if another request inserts the same row first, FirstOrCreate catches the unique constraint violation and returns the existing row with created set to false.
func Fresh ¶
Fresh fetches a fresh copy of m's row from the database without modifying m or loading relationships. If the row no longer exists, Fresh returns *db.NotFoundError.
func FromRoute ¶
FromRoute resolves the model of type T identified by the route parameter param using the route's binding field or the model's route key:
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
return web.Fail(err)
}
The route key defaults to ID unless T defines a RouteKeyName() string method. The parameter string is parsed into the key field's type; if parsing fails or no row matches, FromRoute returns *db.NotFoundError, which maps to HTTP 404.
func FromRouteBy ¶
FromRouteBy resolves the model of type T whose column matches the route parameter param, parsing the parameter into that column's field type:
post, err := model.FromRouteBy[models.Post](r, "post", "slug")
If parsing fails or no row matches, FromRouteBy returns *db.NotFoundError.
func Increment ¶
Increment atomically adds by to column on m's database row (column = column + by) so concurrent requests do not overwrite each other, then updates that field on m with the stored value:
err := model.Increment(ctx, &post, "views", 1)
Increment updates updated_at, runs UpdatingHook, and dispatches Updated just like Update.
func InsertMany ¶
InsertMany bulk-inserts models using multi-row INSERT statements inside a single transaction, suitable for seeding large datasets:
err := model.InsertMany(ctx, comments)
InsertMany skips hooks and events and leaves models unmodified (their IDs remain zero). Unset timestamps are set to the current time, zero IDs and zero db:",default" fields are omitted when zero across all models, and batches stay under 30,000 bound parameters per statement.
func Is ¶
Is reports whether a and b represent the same database row by comparing their non-zero primary keys while ignoring other fields:
fromAuthor := model.Is(comment.User, post.User)
Is returns false if either pointer is nil or has a zero primary key.
func KeyField ¶
func KeyField(t reflect.Type) (reflect.StructField, error)
KeyField returns the ID struct field of model type t for reflection-based callers such as the queue serializer. Its Index is the field's path from t, so it reaches an ID in an embedded struct. It returns an error if t is not a struct with an ID field or if t is a join-row wrapper struct.
func Keys ¶
Keys extracts the primary key of each model in models in order:
posts, err := model.Query[Post]().WhereIn("user_id", model.Keys(users)).Get(ctx)
func Load ¶
Load eager-loads relations onto an already-loaded model, replacing any values already stored in those relationship fields:
post, err := model.Find[Post](ctx, r.PathValue("post"))
if err != nil {
return web.Fail(err)
}
err = model.Load(ctx, &post, "comments.user")
func LoadAvg ¶
LoadAvg populates the model:"avg=relation.column" field on an already-loaded model, as described by Builder.WithAvg.
func LoadCount ¶
LoadCount populates count fields on an already-loaded model, as described by Builder.WithCount:
user, err := model.Find[User](ctx, r.PathValue("user"))
if err != nil {
return web.Fail(err)
}
err = model.LoadCount(ctx, &user, "posts")
When querying multiple models, prefer Builder.WithCount to load counts in a single query.
func LoadExists ¶
LoadExists populates model:"exists=relation" fields on an already-loaded model, as described by Builder.WithExists.
func LoadMany ¶
LoadMany eager-loads relations onto every model in models using one query per relationship, replacing any values already stored in those fields.
func LoadManyMissing ¶
LoadManyMissing loads only the missing relationships across models, running one query per relationship for the subset of models that need it.
func LoadManyQuery ¶
func LoadManyQuery[T, R any](ctx context.Context, models []T, relation string, clauses func(*Builder[R]) *Builder[R]) error
LoadManyQuery eager-loads relation onto every model in models with additional clauses using a single query, applying Limit per parent model.
func LoadMax ¶
LoadMax populates the model:"max=relation.column" field on an already-loaded model, as described by Builder.WithMax.
func LoadMin ¶
LoadMin populates the model:"min=relation.column" field on an already-loaded model, as described by Builder.WithMin.
func LoadMissing ¶
LoadMissing loads only the requested relationships whose fields on m are currently nil, preserving already-loaded relationships without running extra queries:
err := model.LoadMissing(ctx, &post, "user")
Because a missing belongs_to or has_one record leaves the pointer field nil, LoadMissing queries it again. For dotted paths, nested relationships are loaded onto every related model whose nested field is nil, even if the parent relationship was already loaded.
func LoadQuery ¶
func LoadQuery[T, R any](ctx context.Context, m *T, relation string, clauses func(*Builder[R]) *Builder[R]) error
LoadQuery eager-loads relation onto an already-loaded model with additional clauses, as described by Builder.WithQuery:
err := model.LoadQuery(ctx, &user, "posts", func(q *model.Builder[Post]) *model.Builder[Post] {
return q.Latest("id").Limit(5)
})
func LoadSum ¶
LoadSum populates the model:"sum=relation.column" field on an already-loaded model, as described by Builder.WithSum:
err := model.LoadSum(ctx, &user, "posts", "votes")
func MorphName ¶
MorphName returns the morph type string stored in polymorphic type columns for model T. It returns T's MorphName() string method result if defined, or the snake_case form of T's type name (for example, BlogPost returns "blog_post"):
onVideos, err := model.Query[Comment]().Where("commentable_type", "=", model.MorphName[Video]()).Get(ctx)
func Refresh ¶
Refresh reloads m's row from the database in place and re-fetches any relationships that are currently loaded on m. If the row no longer exists, Refresh returns *db.NotFoundError and leaves m unchanged.
func Relate ¶
Relate sets related's foreign key (and morph type for morph_one or morph_many) from m's local key in memory without saving related:
err := model.Relate(&post, "comments", &comment)
For join-table relationships (belongs_to_many, morph_to_many, and morphed_by_many), Relate is a no-op because the link lives in the join table. Relate returns an error if m's local key is NULL, and panics if relation is belongs_to, morph_to, read-only, or does not hold type R.
func Replicate ¶
func Replicate[T any](m T) T
Replicate returns a copy of m prepared for insertion as a new row, with its ID, timestamps, loaded relationships, and aggregate counts cleared:
billing := model.Replicate(shipping) billing.Kind = "billing" err := model.Create(ctx, &billing)
Zero out any additional fields before calling Create to let the database apply their default or NULL values.
func RouteKey ¶
RouteKey returns the route parameter value for value: the specified column when column is non-empty, or the model's route key (ID unless RouteKeyName overrides it). Non-model values are returned unchanged, and join-row wrapper structs resolve through their embedded model. RouteKey returns an error if column does not exist on the model.
func Save ¶
Save updates every non-key, non-created_at column of an existing model, updates UpdatedAt, and reloads m from the stored row. It returns an error if m has a zero ID, or *db.NotFoundError if the row no longer exists.
If *T implements UpdatingHook, Updating runs first. Save then dispatches an Updated event; when listeners are registered, Save locks and reads the previous row in the same transaction to populate Updated.Changes.
func Update ¶
Update writes only the columns in values whose new value differs from m's current field (plus updated_at unless values sets it), then refreshes those fields on m from the database. Values may include db.Expr expressions, which are always written:
err := model.Update(ctx, &post, db.Values{"title": form.Title, "views": db.Raw("views + 1")})
If every entry in values matches m's current fields, Update runs no query, skips hooks, and dispatches no event. Update returns an error if m has a zero ID, or *db.NotFoundError if the row no longer exists. If *T implements UpdatingHook, Updating runs before the write, and Update dispatches an Updated event afterward.
func UpdateJoinRow ¶
func UpdateJoinRow[T, K any](ctx context.Context, m *T, relation string, key K, values db.Values) error
UpdateJoinRow updates extra columns on the join table row linking m to key (a primary key or persisted related model):
err := model.UpdateJoinRow(ctx, &user, "roles", admin.ID, db.Values{"level": "member"})
If the join-row struct declares an UpdatedAt field and values does not set updated_at, UpdateJoinRow updates it automatically. If m is not linked to key, UpdateJoinRow makes no changes and returns nil.
func UpdateOrCreate ¶
func UpdateOrCreate[T any](ctx context.Context, attributes, values db.Values) (m T, created bool, err error)
UpdateOrCreate updates the first model matching attributes with values using Update, or creates a new model from attributes and values using FirstOrCreate when none exists. The created return value reports whether a new row was inserted.
func Upsert ¶
func Upsert[T any](ctx context.Context, models []T, unique []string, update ...string) (int64, error)
Upsert inserts models and updates conflicting rows identified by the unique columns (which must have a unique index), returning the number of affected rows reported by the database.
Pass update to choose which columns are overwritten on conflict; when update is empty, Upsert updates every column except ID, created_at, and unique columns. Zero IDs and zero db:",default" fields are omitted when zero across all models, and timestamps are populated automatically.
Types ¶
type Builder ¶
type Builder[T any] struct { // contains filtered or unexported fields }
Builder constructs and executes queries that return models of type T. Like db.Query, every clause method returns a new Builder without mutating the receiver, so a query can be stored and reused safely.
Column names passed to clauses are validated against T's struct fields; an unknown column panics with the list of valid columns. After a join, qualify columns from other tables with their table name (such as "users.name"); unqualified names are checked against T.
Queries run on the database connection carried by ctx, joining any active transaction. Call Builder.On to target a specific connection instead. Model queries select all columns of T's table by default; use Builder.Select to project columns for a subquery, or start with db.Table for grouped aggregates.
func Query ¶
Query starts a new Builder for model type T:
posts, err := model.Query[Post]().Where("votes", ">", 100).Get(ctx)
Query panics if T is not a struct with an ID field, or if T is a join-row wrapper type (read those through Related or Builder.With instead).
func Related ¶
Related returns a Builder scoped to m's related models of type R on relation:
comments, err := model.Related[Comment](&post, "comments").Latest("id").Get(ctx)
Any additional clauses chain onto the relationship filter with AND, so wrap OR conditions in Builder.WhereGroup:
model.Related[Comment](&post, "comments").WhereGroup(func(q *model.Builder[Comment]) *model.Builder[Comment] {
return q.Where("approved", "=", true).OrWhere("user_id", "=", user.ID)
})
Related panics if relation is a morph_to relationship (use Load or FindMorph instead) or does not hold type R.
func (*Builder[T]) Avg ¶
Avg returns the average of column across matching models as V. Use a pointer type such as *float64 when the query may match zero rows, in which case Avg returns nil.
func (*Builder[T]) Chunk ¶
Chunk iterates over matching models in offset-paginated batches of size, loading any relationships requested via Builder.With for each batch. Rows tied in the query's ORDER BY are ordered by ID for deterministic pages, and the query's own limit and offset still apply.
Because Chunk uses OFFSET, modifying or deleting matching rows during iteration can skip records; use Builder.ChunkByID when mutating rows in the loop.
func (*Builder[T]) ChunkByID ¶
ChunkByID iterates over matching models in batches of size ordered by ascending primary key, as described by db.Query.ChunkByID, loading any relationships requested via Builder.With for each batch. Unlike Builder.Chunk, ChunkByID is safe when the loop updates or deletes the matched rows.
func (*Builder[T]) ChunkByIDDesc ¶
ChunkByIDDesc iterates over matching models in batches of size ordered by descending primary key, loading any relationships requested via Builder.With for each batch.
func (*Builder[T]) CountDistinct ¶
CountDistinct returns the number of distinct non-NULL values in column across matching models.
func (*Builder[T]) Cursor ¶
Cursor executes a single streaming query and yields matching models one by one without eager loading relationships. Cursor returns an error for join-row wrapper types; use Builder.LazyByID for those.
func (*Builder[T]) CursorPaginate ¶
func (b *Builder[T]) CursorPaginate(ctx context.Context, page pagination.Page) (*pagination.CursorPaginator[T], error)
CursorPaginate loads the page of models after or before page.Cursor into a *pagination.CursorPaginator. If the query has no explicit ordering, it orders by primary key:
posts, err := model.Query[Post]().Latest("created_at").Latest("id").CursorPaginate(r, r.Page(15))
func (*Builder[T]) Decrement ¶
Decrement atomically subtracts by from column on every matching row directly in the database and returns the number of affected rows.
func (*Builder[T]) Delete ¶
Delete removes every matching row directly in the database without loading models, running hooks, or dispatching events, and returns the number of deleted rows.
func (*Builder[T]) Distinct ¶
Distinct returns each matching model at most once, which is useful when a join matches the same model row multiple times.
func (*Builder[T]) DoesntHave ¶
DoesntHave keeps models that have no related model on relation.
func (*Builder[T]) Find ¶
Find returns the model whose primary key equals key. String keys are parsed into the ID field's Go type (so route parameters work directly), and unparseable strings return *db.NotFoundError. Non-string keys are bound directly.
func (*Builder[T]) FindMany ¶
FindMany returns the models whose primary keys match keys, skipping any missing keys:
posts, err := model.Query[Post]().FindMany(ctx, form.PostIDs)
func (*Builder[T]) First ¶
First executes the query and returns the first matching model. If no row matches, First returns *db.NotFoundError, which maps to HTTP 404.
func (*Builder[T]) ForPage ¶
ForPage sets OFFSET and LIMIT for a 1-based page number of size perPage.
func (*Builder[T]) FromRoute ¶
FromRoute resolves the model matching both the builder's clauses and the route parameter param, using the route's explicit binding column (such as {post:slug}) or the model's route key. Scoping through a query or relationship ensures a nested route returns 404 for another parent's child:
post, err := model.Related[models.Post](&user, "posts").FromRoute(r, "post")
func (*Builder[T]) FromRouteBy ¶
FromRouteBy resolves the model matching both the builder's clauses and the route parameter param on column, returning *db.NotFoundError if parsing fails or no row matches.
func (*Builder[T]) Get ¶
Get executes the query and returns all matching models along with any relationships requested via Builder.With. When no rows match, Get returns an empty non-nil slice so JSON encoding produces [].
func (*Builder[T]) GroupBy ¶
GroupBy groups rows by columns, typically paired with Builder.Having or Builder.HavingRaw when filtering on joined rows:
model.Query[Post]().
Join("comments", "comments.post_id", "=", "id").
GroupBy("id").
HavingRaw("count(*) > ?", 10)
func (*Builder[T]) Has ¶
Has keeps models that have at least one related model on relation:
authors, err := model.Query[User]().Has("posts").Get(ctx)
Use dot notation such as "posts.comments" to require a chain of related models.
func (*Builder[T]) HasCount ¶
HasCount keeps models whose related row count on relation satisfies operator (=, <>, !=, <, <=, >, or >=) against count:
prolific, err := model.Query[User]().HasCount("posts", ">=", 3).Get(ctx)
For a dotted path such as "posts.comments", HasCount keeps models that have at least one intermediate record whose final relationship count satisfies the condition. HasCount panics if operator is invalid or relation is morph_to.
func (*Builder[T]) Having ¶
Having adds a HAVING condition on grouped rows, as described by db.Query.Having.
func (*Builder[T]) HavingRaw ¶
HavingRaw adds a raw SQL HAVING condition on grouped rows. Column names inside sql are not checked against T.
func (*Builder[T]) InOrderOf ¶
InOrderOf sorts models by column matching the order of values, placing rows whose column value is not listed last.
func (*Builder[T]) InRandomOrder ¶
InRandomOrder sorts matching models in random order.
func (*Builder[T]) Increment ¶
Increment atomically adds by to column on every matching row directly in the database and returns the number of affected rows:
model.Query[Post]().Where("user_id", "=", user.ID).Increment(ctx, "votes", 1)
Like Builder.Update, Increment updates updated_at automatically when T has an UpdatedAt field and does not run hooks or dispatch events.
func (*Builder[T]) Join ¶
Join adds an INNER JOIN to table, such as Join("users", "users.id", "=", "user_id").
func (*Builder[T]) JoinOn ¶
JoinOn adds an INNER JOIN to table using the join conditions built by on, as described by db.Query.JoinOn. Column names inside on are not checked against T.
func (*Builder[T]) LazyByID ¶
LazyByID iterates over matching models one by one, fetching batches of size ordered by ascending primary key like Builder.ChunkByID.
func (*Builder[T]) LazyByIDDesc ¶
LazyByIDDesc iterates over matching models one by one, fetching batches of size ordered by descending primary key like Builder.ChunkByIDDesc.
func (*Builder[T]) LeftJoinOn ¶
LeftJoinOn adds a LEFT JOIN to table using the join conditions built by on.
func (*Builder[T]) LimitPer ¶
LimitPer applies Builder.Limit and Builder.Offset independently within each partition of column, as described by db.Query.LimitPer. For example, this fetches each user's three newest posts:
model.Query[Post]().WhereIn("user_id", ids).Latest("id").Limit(3).LimitPer("user_id")
func (*Builder[T]) LockForUpdate ¶
LockForUpdate acquires an exclusive row lock (FOR UPDATE) on selected rows until the current transaction ends, as described by db.Query.LockForUpdate.
func (*Builder[T]) Max ¶
Max returns the largest value of column across matching models as V. Use a pointer type when the query may match zero rows, in which case Max returns nil.
func (*Builder[T]) Min ¶
Min returns the smallest value of column across matching models as V. Use a pointer type when the query may match zero rows, in which case Min returns nil.
func (*Builder[T]) NoWait ¶
NoWait causes the query to fail immediately if another transaction already holds a lock on a matching row (NOWAIT).
func (*Builder[T]) On ¶
On returns a copy of the builder that runs its query and loads eager relationships on conn instead of the connection carried by ctx.
func (*Builder[T]) OrDoesntHave ¶
OrDoesntHave adds a Builder.DoesntHave condition joined to preceding conditions with OR.
func (*Builder[T]) OrHas ¶
OrHas adds a Builder.Has condition joined to preceding conditions with OR.
func (*Builder[T]) OrWhereBelongsTo ¶
OrWhereBelongsTo adds a Builder.WhereBelongsTo condition joined to preceding conditions with OR.
func (*Builder[T]) OrWhereDoesntHave ¶
func (b *Builder[T]) OrWhereDoesntHave[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
OrWhereDoesntHave adds a Builder.WhereDoesntHave condition joined to preceding conditions with OR.
func (*Builder[T]) OrWhereDoesntHaveRelation ¶
func (b *Builder[T]) OrWhereDoesntHaveRelation(relation, column, operator string, value any) *Builder[T]
OrWhereDoesntHaveRelation adds a Builder.WhereDoesntHaveRelation condition joined to preceding conditions with OR.
func (*Builder[T]) OrWhereDoesntHaveRelationEq ¶
OrWhereDoesntHaveRelationEq adds a Builder.WhereDoesntHaveRelationEq condition joined to preceding conditions with OR.
func (*Builder[T]) OrWhereEq ¶
OrWhereEq adds an OR equality condition (column = value), as in Builder.OrWhere.
func (*Builder[T]) OrWhereGe ¶
OrWhereGe adds an OR greater-than-or-equal condition (column >= value), as in Builder.OrWhere.
func (*Builder[T]) OrWhereGroup ¶
OrWhereGroup wraps the conditions built by group in parentheses and joins them with OR.
func (*Builder[T]) OrWhereGt ¶
OrWhereGt adds an OR greater-than condition (column > value), as in Builder.OrWhere.
func (*Builder[T]) OrWhereHas ¶
func (b *Builder[T]) OrWhereHas[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
OrWhereHas adds a Builder.WhereHas condition joined to preceding conditions with OR:
users, err := model.Query[User]().
WhereLike("email", "%@laravel.com", false).
OrWhereHas("posts", func(q *model.Builder[Post]) *model.Builder[Post] {
return q.Where("votes", ">", 100)
}).
Get(ctx)
func (*Builder[T]) OrWhereLe ¶
OrWhereLe adds an OR less-than-or-equal condition (column <= value), as in Builder.OrWhere.
func (*Builder[T]) OrWhereLike ¶
OrWhereLike keeps models whose column matches the SQL LIKE pattern, joined with OR.
func (*Builder[T]) OrWhereLt ¶
OrWhereLt adds an OR less-than condition (column < value), as in Builder.OrWhere.
func (*Builder[T]) OrWhereNe ¶
OrWhereNe adds an OR inequality condition (column != value), as in Builder.OrWhere.
func (*Builder[T]) OrWhereNotLike ¶
OrWhereNotLike keeps models whose column does not match the SQL LIKE pattern, joined with OR.
func (*Builder[T]) OrWhereRaw ¶
OrWhereRaw adds a raw SQL WHERE condition joined with OR. Column names inside sql are not checked against T.
func (*Builder[T]) OrWhereRelation ¶
OrWhereRelation adds a Builder.WhereRelation condition joined to preceding conditions with OR.
func (*Builder[T]) OrWhereRelationEq ¶
OrWhereRelationEq adds a Builder.WhereRelationEq condition joined to preceding conditions with OR.
func (*Builder[T]) OrderBy ¶
OrderBy sorts models by column in ascending order. Additional OrderBy calls break ties in earlier sort columns.
func (*Builder[T]) OrderByCount ¶
OrderByCount sorts models by their related row count on relation in ascending order (fewest first), treating models with no related rows as 0. OrderByCount panics if relation is a morph_to relationship.
func (*Builder[T]) OrderByCountDesc ¶
OrderByCountDesc sorts models by their related row count on relation in descending order (most first), treating models with no related rows as 0:
busiest, err := model.Query[User]().OrderByCountDesc("posts").Limit(10).Get(ctx)
func (*Builder[T]) OrderByDesc ¶
OrderByDesc sorts models by column in descending order.
func (*Builder[T]) OrderByDirection ¶
OrderByDirection sorts models by column in the given db.Direction, such as one parsed with db.ParseDirection.
func (*Builder[T]) OrderByRaw ¶
OrderByRaw sorts models by a raw SQL ORDER BY expression.
func (*Builder[T]) OrderByRelevance ¶
OrderByRelevance sorts matching models by full-text search relevance, best match first.
func (*Builder[T]) OrderBySub ¶
OrderBySub sorts models in ascending order by a scalar subquery returning one column of one row, such as each user's most recent login:
lastLogin := db.Table("logins").SelectRaw("max(created_at)").WhereColumn("logins.user_id", "=", "users.id")
users, err := model.Query[User]().OrderBySub(lastLogin).Get(ctx)
func (*Builder[T]) OrderBySubDesc ¶
OrderBySubDesc sorts models in descending order by a scalar subquery.
func (*Builder[T]) OrderByVectorDistance ¶
OrderByVectorDistance sorts models by cosine distance from embedding, nearest first.
func (*Builder[T]) Paginate ¶
func (b *Builder[T]) Paginate(ctx context.Context, page pagination.Page) (*pagination.Paginator[T], error)
Paginate counts all matching models and loads the requested page into a *pagination.Paginator, including any relationships requested via Builder.With:
posts, err := model.Query[Post]().Latest("id").Paginate(r, r.Page(15))
func (*Builder[T]) Pluck ¶
Pluck returns a slice containing the value of column from every matching model:
titles, err := model.Query[Post]().OrderBy("title").Pluck[string](ctx, "title")
func (*Builder[T]) Reorder ¶
Reorder clears any previously added ORDER BY clauses so subsequent ordering calls start fresh.
func (*Builder[T]) RightJoin ¶
RightJoin adds a RIGHT JOIN to table, as described by db.Query.RightJoin.
func (*Builder[T]) RightJoinOn ¶
RightJoinOn adds a RIGHT JOIN to table using the join conditions built by on.
func (*Builder[T]) Scope ¶
Scope applies a reusable query function to the builder and wraps any WHERE conditions it adds in parentheses so an OrWhere inside the scope cannot widen outer conditions:
func Popular(q *model.Builder[Post]) *model.Builder[Post] {
return q.Where("votes", ">", 100).WhereNotNull("published_at")
}
posts, err := model.Query[Post]().Scope(Popular).Get(ctx)
func (*Builder[T]) Select ¶
Select converts the builder into a *db.Query projecting only columns, suitable for use as a subquery in another query:
banned := model.Query[User]().Where("banned", "=", true).Select("id")
posts, err := model.Query[Post]().WhereIn("user_id", banned).Get(ctx)
Column names are validated against T's struct fields.
func (*Builder[T]) SharedLock ¶
SharedLock acquires a shared row lock on selected rows until the current transaction ends, preventing concurrent updates.
func (*Builder[T]) SimplePaginate ¶
func (b *Builder[T]) SimplePaginate(ctx context.Context, page pagination.Page) (*pagination.SimplePaginator[T], error)
SimplePaginate loads the requested page into a *pagination.SimplePaginator, fetching one extra row instead of running a count query to determine whether another page follows.
func (*Builder[T]) SkipLocked ¶
SkipLocked skips rows already locked by another transaction (SKIP LOCKED), allowing concurrent workers to claim distinct models.
func (*Builder[T]) Sole ¶
Sole returns the single matching model. It returns *db.NotFoundError if no row matches, or *db.MultipleRowsError if more than one row matches.
func (*Builder[T]) Sum ¶
Sum returns the sum of column across matching models as V, returning 0 when no rows match:
votes, err := model.Query[Post]().Where("user_id", "=", user.ID).Sum[int64](ctx, "votes")
func (*Builder[T]) ToSQL ¶
ToSQL returns the generated SQL SELECT statement and its bound arguments for the connection carried by ctx.
func (*Builder[T]) Union ¶
Union combines this query with other and removes duplicate rows, as described by db.Query.Union. Ordering, limit, and offset apply to the combined result, so chain them after Union:
model.Query[Post]().Where("votes", ">", 100).Union(model.Query[Post]().Where("featured", "=", true)).Latest("id")
Because UNION compares full rows, PostgreSQL requires jsonb rather than json columns on models used with Union.
func (*Builder[T]) Update ¶
Update updates values on every matching row directly in the database without loading models, running hooks, or dispatching events, and returns the number of affected rows. If T has an UpdatedAt field and values does not include updated_at, Update sets updated_at automatically.
func (*Builder[T]) Value ¶
Value returns a single column from the first matching model as V without scanning the entire struct. If no row matches, Value returns *db.NotFoundError:
title, err := model.Query[Post]().Latest("votes").Value[string](ctx, "title")
func (*Builder[T]) When ¶
When applies fn to the builder if condition is true, and returns b unchanged otherwise. Use it for conditional filters based on user input.
func (*Builder[T]) Where ¶
Where adds a WHERE condition, such as Where("votes", ">", 100), as db.Query.Where does. For a field tagged db:",embed", Where compares every column the embedded struct spans with "=" (for example, Where("total", "=", price) matches both total_amount and total_currency).
func (*Builder[T]) WhereAfterToday ¶
WhereAfterToday keeps models whose column falls after today's UTC date.
func (*Builder[T]) WhereBeforeToday ¶
WhereBeforeToday keeps models whose column falls before today's UTC date.
func (*Builder[T]) WhereBelongsTo ¶
WhereBelongsTo filters models whose belongs_to or morph_to relationship points to parent, which must be a non-nil pointer to a model:
posts, err := model.Query[Post]().WhereBelongsTo("user", &user).Get(ctx)
comments, err := model.Query[Comment]().WhereBelongsTo("commentable", &post).Get(ctx)
For a morph_to relationship, WhereBelongsTo constrains both the morph type and key columns so another model type with the same ID cannot match. WhereBelongsTo panics if relation is not belongs_to or morph_to, or if parent does not match the relationship type.
func (*Builder[T]) WhereBetween ¶
WhereBetween constrains column to values in the inclusive range [low, high].
func (*Builder[T]) WhereColumn ¶
WhereColumn compares two columns directly, such as WhereColumn("updated_at", ">", "created_at").
func (*Builder[T]) WhereDate ¶
WhereDate compares the date portion of a date or timestamp column, such as WhereDate("created_at", "=", "2026-10-31"), as described by db.Query.WhereDate.
func (*Builder[T]) WhereDay ¶
WhereDay compares the day of the month (1 through 31) of a date or timestamp column.
func (*Builder[T]) WhereDistinctFrom ¶
WhereDistinctFrom keeps models whose column differs from value using null-safe comparison (IS DISTINCT FROM), as described by db.Query.WhereDistinctFrom.
func (*Builder[T]) WhereDoesntHave ¶
func (b *Builder[T]) WhereDoesntHave[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
WhereDoesntHave keeps models that have no related model matching query's clauses, including models with no related models at all:
unrecognized, err := model.Query[User]().
WhereDoesntHave("posts", func(q *model.Builder[Post]) *model.Builder[Post] {
return q.Where("votes", ">", 100)
}).
Get(ctx)
func (*Builder[T]) WhereDoesntHaveRelation ¶
func (b *Builder[T]) WhereDoesntHaveRelation(relation, column, operator string, value any) *Builder[T]
WhereDoesntHaveRelation keeps models that have no related model on relation where column satisfies operator against value, including models with no related models at all:
unflagged, err := model.Query[User]().WhereDoesntHaveRelation("posts", "status", "=", "flagged").Get(ctx)
WhereDoesntHaveRelation panics if relation does not exist or is a morph_to relationship.
func (*Builder[T]) WhereDoesntHaveRelationEq ¶
WhereDoesntHaveRelationEq keeps models that have no related model on relation where column equals value, matching Builder.WhereDoesntHaveRelation:
unflagged, err := model.Query[User]().WhereDoesntHaveRelationEq("posts", "status", "flagged").Get(ctx)
func (*Builder[T]) WhereEq ¶
WhereEq adds an AND equality condition (column = value), as in Builder.Where.
func (*Builder[T]) WhereExists ¶
WhereExists keeps models for which sub returns at least one row, as described by db.Query.WhereExists.
func (*Builder[T]) WhereFullText ¶
WhereFullText filters models using full-text search across search.Columns, as described by db.Query.WhereFullText.
func (*Builder[T]) WhereFuture ¶
WhereFuture keeps models whose column timestamp is after the application's current time.
func (*Builder[T]) WhereGe ¶
WhereGe adds an AND greater-than-or-equal condition (column >= value), as in Builder.Where.
func (*Builder[T]) WhereGroup ¶
WhereGroup wraps the conditions built by group in parentheses and joins them with AND.
func (*Builder[T]) WhereGt ¶
WhereGt adds an AND greater-than condition (column > value), as in Builder.Where.
func (*Builder[T]) WhereHas ¶
func (b *Builder[T]) WhereHas[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
WhereHas keeps models that have at least one related model matching query's clauses:
popular, err := model.Query[User]().
WhereHas("posts", func(q *model.Builder[Post]) *model.Builder[Post] {
return q.Where("votes", ">", 100)
}).
Get(ctx)
R must match the relationship's model type (or for a dotted path, the final segment's model type). For a morph_to relationship, set R to one of the concrete models implementing the relationship interface; WhereHas keeps only models pointing to a matching row of type R.
func (*Builder[T]) WhereHasCount ¶
func (b *Builder[T]) WhereHasCount[R any](relation, operator string, count int, query func(*Builder[R]) *Builder[R]) *Builder[T]
WhereHasCount keeps models whose count of related rows matching query satisfies operator against count, as described by Builder.HasCount:
popular, err := model.Query[User]().
WhereHasCount("posts", ">=", 3, func(q *model.Builder[Post]) *model.Builder[Post] {
return q.Where("votes", ">", 100)
}).
Get(ctx)
func (*Builder[T]) WhereIn ¶
WhereIn constrains column to match any element of values (a slice or a *db.Query subquery). An empty slice matches no rows.
func (*Builder[T]) WhereJSONContains ¶
WhereJSONContains constrains a JSON column or path to documents that contain value, as described by db.Query.WhereJSONContains:
model.Query[User]().WhereJSONContains("options->languages", "en")
func (*Builder[T]) WhereJSONContainsKey ¶
WhereJSONContainsKey keeps models whose JSON column contains the given key path, such as "options->language".
func (*Builder[T]) WhereJSONDoesntContain ¶
WhereJSONDoesntContain constrains a JSON column or path to documents that do not contain value.
func (*Builder[T]) WhereJSONDoesntContainKey ¶
WhereJSONDoesntContainKey keeps models whose JSON column does not contain the given key path.
func (*Builder[T]) WhereJSONLength ¶
WhereJSONLength constrains the length of the JSON array at column or path, such as WhereJSONLength("options->languages", ">", 1).
func (*Builder[T]) WhereLe ¶
WhereLe adds an AND less-than-or-equal condition (column <= value), as in Builder.Where.
func (*Builder[T]) WhereLike ¶
WhereLike keeps models whose column matches the SQL LIKE pattern, as described by db.Query.WhereLike.
func (*Builder[T]) WhereLt ¶
WhereLt adds an AND less-than condition (column < value), as in Builder.Where.
func (*Builder[T]) WhereMonth ¶
WhereMonth compares the month of a date or timestamp column (1 for January through 12 for December).
func (*Builder[T]) WhereNe ¶
WhereNe adds an AND inequality condition (column != value), as in Builder.Where.
func (*Builder[T]) WhereNotDistinctFrom ¶
WhereNotDistinctFrom keeps models whose column equals value using null-safe comparison (IS NOT DISTINCT FROM).
func (*Builder[T]) WhereNotExists ¶
WhereNotExists keeps models for which sub returns no rows.
func (*Builder[T]) WhereNotIn ¶
WhereNotIn constrains column to exclude all elements of values (a slice or a *db.Query subquery).
func (*Builder[T]) WhereNotLike ¶
WhereNotLike keeps models whose column does not match the SQL LIKE pattern.
func (*Builder[T]) WhereNotNull ¶
WhereNotNull constrains column to non-NULL values.
func (*Builder[T]) WhereNowOrFuture ¶
WhereNowOrFuture keeps models whose column timestamp is at or after the application's current time.
func (*Builder[T]) WhereNowOrPast ¶
WhereNowOrPast keeps models whose column timestamp is at or before the application's current time.
func (*Builder[T]) WherePast ¶
WherePast keeps models whose column timestamp is before the application's current time.
func (*Builder[T]) WhereRaw ¶
WhereRaw adds a raw SQL WHERE condition joined with AND. Column names inside sql are not checked against T.
func (*Builder[T]) WhereRelation ¶
WhereRelation keeps models that have at least one related model on relation where column satisfies operator against value, avoiding a Builder.WhereHas callback for single-condition filters:
popular, err := model.Query[User]().WhereRelation("posts", "votes", ">", 100).Get(ctx)
Dotted paths such as "posts.comments" filter the final relationship in the chain. Embedded struct columns tagged db:",embed" compare every column they span, matching Builder.Where. WhereRelation panics if relation does not exist or is a morph_to relationship.
func (*Builder[T]) WhereRelationEq ¶
WhereRelationEq keeps models that have at least one related model on relation where column equals value, matching Builder.WhereRelation:
publishers, err := model.Query[User]().WhereRelationEq("posts", "published", true).Get(ctx)
func (*Builder[T]) WhereSub ¶
WhereSub compares the scalar value returned by sub against value using operator, as described by db.Query.WhereSub.
func (*Builder[T]) WhereTime ¶
WhereTime compares the time-of-day portion of a date or timestamp column, such as WhereTime("created_at", ">=", "17:00:00").
func (*Builder[T]) WhereToday ¶
WhereToday keeps models whose column falls on today's UTC date.
func (*Builder[T]) WhereTodayOrAfter ¶
WhereTodayOrAfter keeps models whose column falls on or after today's UTC date.
func (*Builder[T]) WhereTodayOrBefore ¶
WhereTodayOrBefore keeps models whose column falls on or before today's UTC date.
func (*Builder[T]) WhereVectorSimilarTo ¶
func (b *Builder[T]) WhereVectorSimilarTo(column string, embedding db.Vector, minSimilarity float64) *Builder[T]
WhereVectorSimilarTo filters models whose vector column has a cosine similarity of at least minSimilarity to embedding and orders them most similar first, as described by db.Query.WhereVectorSimilarTo.
func (*Builder[T]) With ¶
With eager-loads the named relationships into every model returned by the query using one query per relationship, avoiding N+1 queries:
posts, err := model.Query[Post]().With("user", "comments").Get(ctx)
Use dot notation such as "comments.user" to load nested relationships. With panics if any relationship name does not exist on the corresponding model.
func (*Builder[T]) WithAvg ¶
WithAvg computes the average of column across each model's related rows and stores the result in the field tagged model:"avg=relation.column". Use a pointer type such as *float64 when a model may have no related rows, in which case the field remains nil.
func (*Builder[T]) WithCount ¶
WithCount populates each model's count field (tagged model:"count" and named after the relationship plus Count) without loading the related models:
type Post struct {
// ...
Comments []Comment `json:"comments,omitzero" model:"has_many"`
CommentsCount *int `json:"comments_count,omitzero" model:"count"`
}
posts, err := model.Query[Post]().WithCount("comments").Get(ctx)
Using *int with omitzero leaves the count out of JSON when it wasn't loaded, while a loaded count of 0 still encodes as 0. Plain integer fields are also supported.
WithCount panics if any relation does not exist, is a morph_to relationship, or has no matching count field on T.
func (*Builder[T]) WithCountQuery ¶
func (b *Builder[T]) WithCountQuery[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
WithCountQuery populates each model's count field for relation like Builder.WithCount, counting only related models that match query's clauses, such as approved comments.
func (*Builder[T]) WithExists ¶
WithExists populates each model's boolean field (*bool or bool) tagged model:"exists=relation" indicating whether at least one related row exists, without loading the related models. Using *bool with omitzero leaves the field out of JSON when unloaded while still encoding false when loaded.
func (*Builder[T]) WithMax ¶
WithMax computes the maximum value of column across each model's related rows and stores the result in the field tagged model:"max=relation.column". Use a pointer field when a model may have no related rows so it remains nil.
func (*Builder[T]) WithMin ¶
WithMin computes the minimum value of column across each model's related rows and stores the result in the field tagged model:"min=relation.column". Use a pointer field when a model may have no related rows so it remains nil.
func (*Builder[T]) WithQuery ¶
func (b *Builder[T]) WithQuery[R any](relation string, query func(*Builder[R]) *Builder[R]) *Builder[T]
WithQuery eager-loads relation with additional query clauses applied to the related models, such as loading each user's three newest posts:
users, err := model.Query[User]().
WithQuery("posts", func(q *model.Builder[Post]) *model.Builder[Post] {
return q.With("comments").Latest("id").Limit(3)
}).
Get(ctx)
Limit and Offset apply per parent model rather than across the whole result set, and nested Builder.With calls inside query load further levels. For a dotted path, query constrains the final segment. For a morph_to relationship, set R to one of the concrete models implementing the relationship interface; query applies only to rows of type R.
func (*Builder[T]) WithSum ¶
WithSum computes the sum of column across each model's related rows without loading them and stores the result in the field tagged model:"sum=relation.column":
type User struct {
// ...
Posts []Post `json:"posts,omitzero" model:"has_many"`
PostsVotes *int64 `json:"posts_votes,omitzero" model:"sum=posts.votes"`
}
users, err := model.Query[User]().WithSum("posts", "votes").Get(ctx)
Models with no related rows receive nil for a pointer field (or 0 for a value field).
type Change ¶
type Change struct {
// Column is the database column name that changed.
Column string
// Old is the field value before the update.
Old any
// New is the field value after the update.
New any
}
Change records a single column modification made by an update, capturing its value before and after the write.
type Changes ¶
type Changes[K any] struct { // Attached holds the keys for which new join rows were inserted. Attached []K `json:"attached"` // Detached holds the keys whose existing join rows were deleted. Detached []K `json:"detached"` // Updated holds the keys whose existing join rows had columns updated. Updated []K `json:"updated"` }
Changes reports which related keys were attached, detached, or updated by Sync, SyncWith, or Toggle.
func Sync ¶
Sync reconciles m's join-table relationship inside a transaction so it links to exactly keys, attaching missing keys and detaching any others:
changes, err := model.Sync(ctx, &post, "tags", form.TagIDs)
Pass an empty slice to detach all linked records. Use SyncWith to set extra join table columns on attached and kept rows.
func SyncWith ¶
func SyncWith[T any, K comparable](ctx context.Context, m *T, relation string, links map[K]db.Values) (Changes[K], error)
SyncWith reconciles m's join-table relationship like Sync while writing the extra join table columns in links on both newly attached rows and existing rows that remain linked:
changes, err := model.SyncWith(ctx, &user, "roles", map[int64]db.Values{
owner.ID: {"level": "owner"},
member.ID: {"level": "member"},
})
type Created ¶
type Created[T any] struct { Model T }
Created is the event dispatched after Create, FirstOrCreate, UpdateOrCreate, or CreateRelated inserts a model row. Model holds the record as stored in the database.
type CreatingHook ¶
CreatingHook is implemented by models that run logic before Create, FirstOrCreate, UpdateOrCreate, or CreateRelated inserts a new row, such as deriving a slug from a title:
func (a *Article) Creating(ctx context.Context) error {
a.Slug = slug(a.Title)
return nil
}
Creating runs inside the insert transaction, so any queries or writes made with ctx join and roll back with it. Field changes made by Creating are written to the inserted row. Returning an error aborts the insert and returns that error to the caller.
type Deleted ¶
type Deleted[T any] struct { Model T }
Deleted is the event dispatched after Delete removes a model row. Model holds the deleted record.
type DeletingHook ¶
DeletingHook is implemented by models that run logic before Delete removes a row. Deleting runs inside the delete transaction, and returning an error aborts the deletion and returns that error to the caller.
type ExistsRule ¶
type ExistsRule[T any] struct { // contains filtered or unexported fields }
ExistsRule is the validation.Rule returned by Exists.
func Exists ¶
func Exists[T any](column ...string) ExistsRule[T]
Exists returns a validation.Rule that requires T's table to contain a row whose column matches the field's value, such as confirming a chosen category exists:
rule.Field(&f.CategoryID, rule.Required, model.Exists[Category]())
When column is omitted, Exists checks T's ID column. Pass a column name to match against another column on T:
rule.Field(&f.CategorySlug, rule.Required, model.Exists[Category]("slug"))
When validating elements of a list with go.laravel.com/validation/rule.Each, Exists runs one query per item. Pair it with Max to bound list length and Bail to stop after the first failure.
Exists panics if T is not a model struct, if T is a join-row wrapper type, if more than one column is passed, or if column is not one of T's columns.
func (ExistsRule[T]) Message ¶
func (e ExistsRule[T]) Message(text string) ExistsRule[T]
Message returns a copy of e that reports text when validation fails.
func (ExistsRule[T]) Validate ¶
func (e ExistsRule[T]) Validate(ctx context.Context, f validation.Field) error
Validate queries the database and returns a validation.Failure if no matching row exists, or any database query error.
func (ExistsRule[T]) Where ¶
func (e ExistsRule[T]) Where(column string, value any) ExistsRule[T]
Where restricts the existence check to rows where column equals value, or where column is NULL when value is nil:
model.Exists[Category]().Where("archived_at", nil)
Where panics if column is not one of T's columns.
func (ExistsRule[T]) WhereGroup ¶
func (e ExistsRule[T]) WhereGroup(filter func(q *Builder[T]) *Builder[T]) ExistsRule[T]
WhereGroup restricts the existence check to rows matching the grouped query conditions built by filter, for predicates that ExistsRule.Where cannot express:
model.Exists[Category]().WhereGroup(func(q *model.Builder[Category]) *model.Builder[Category] {
return q.WhereEq("visibility", "public").OrWhereEq("owner_id", userID)
})
Conditions are wrapped in parentheses so OrWhere clauses stay scoped to the group.
type Request ¶
Request is the subset of an HTTP request needed by FromRoute and FromRouteBy: a context carrying the application scope and a PathValue lookup for route parameters. *web.Request implements Request.
type UniqueRule ¶
type UniqueRule[T any] struct { // contains filtered or unexported fields }
UniqueRule is the validation.Rule returned by Unique.
func Unique ¶
func Unique[T any](column ...string) UniqueRule[T]
Unique returns a validation.Rule that fails when T's table already contains a row whose column matches the field's value, such as an email address that is already registered:
rule.Field(&f.Email, rule.Required, rule.Email, model.Unique[User]())
When column is omitted, Unique checks the column on T matching the validated field's name (such as "email" for Email). Pass a column name when the form field and model column differ:
rule.Field(&f.NewEmail, rule.Required, rule.Email, model.Unique[User]("email"))
The query runs against the database connection attached to the validation context (which r.Validate sets to the request). Comparisons use the column's database collation, so a case-insensitive MySQL column treats "Taylor@example.com" and "taylor@example.com" as equal, while PostgreSQL compares strings strictly by default.
Unique panics if T is not a model struct, if T is a join-row wrapper type, if more than one column is passed, or if column is not one of T's columns. When column is omitted, Validate panics if T has no column matching the validated field's name.
Because Unique checks the table before the handler writes to it, two concurrent requests with the same value can both pass validation. Back the column with a unique index and translate constraint violations with go.laravel.com/db.IsUniqueViolation.
func (UniqueRule[T]) Ignore ¶
func (u UniqueRule[T]) Ignore(target any) UniqueRule[T]
Ignore excludes a row from the uniqueness check, such as allowing a user to save their profile without changing their own email address:
rule.Field(&f.Email, rule.Required, rule.Email, model.Unique[User]().Ignore(user))
Pass a T value, a *T pointer, or a raw ID matching T's ID column. Passing nil or a typed nil pointer ignores no rows. Ignore panics if target is a struct or pointer to a struct other than T or T's ID type.
func (UniqueRule[T]) IgnoreCase ¶
func (u UniqueRule[T]) IgnoreCase() UniqueRule[T]
IgnoreCase makes the uniqueness check compare text without regard to case, using lower(column) = lower(value) across PostgreSQL, MySQL, and SQLite:
rule.Field(&f.Email, rule.Required, rule.Email, model.Unique[User]().IgnoreCase())
func (UniqueRule[T]) Message ¶
func (u UniqueRule[T]) Message(text string) UniqueRule[T]
Message returns a copy of u that reports text when validation fails.
func (UniqueRule[T]) Validate ¶
func (u UniqueRule[T]) Validate(ctx context.Context, f validation.Field) error
Validate queries the database and returns a validation.Failure if a matching row already exists, or any database query error.
func (UniqueRule[T]) Where ¶
func (u UniqueRule[T]) Where(column string, value any) UniqueRule[T]
Where restricts the uniqueness check to rows where column equals value, or where column is NULL when value is nil:
model.Unique[Member]().Where("team_id", teamID)
Where panics if column is not one of T's columns.
func (UniqueRule[T]) WhereGroup ¶
func (u UniqueRule[T]) WhereGroup(filter func(q *Builder[T]) *Builder[T]) UniqueRule[T]
WhereGroup restricts the uniqueness check to rows matching the grouped query conditions built by filter, for predicates that UniqueRule.Where cannot express:
model.Unique[Member]().WhereGroup(func(q *model.Builder[Member]) *model.Builder[Member] {
return q.Where("role", "<>", "guest").OrWhereNull("left_at")
})
Conditions are wrapped in parentheses so OrWhere clauses stay scoped to the group.
type Updated ¶
Updated is the event dispatched after Update, Save, or UpdateOrCreate modifies a model row. Model holds the updated record, and Changes lists every column whose value changed.
type UpdatingHook ¶
UpdatingHook is implemented by models that run logic before Update, Save, or UpdateOrCreate modifies an existing row. The hook receives the pending column updates in values and may inspect, add, modify, or delete entries:
func (a *Article) Updating(ctx context.Context, values db.Values) error {
if a.Locked {
return ErrLocked
}
if title, ok := values["title"].(string); ok {
values["slug"] = slug(title)
}
return nil
}
For Update, the receiver holds the model's fields before the update; for Save, it holds the fields your code modified. Updating runs inside the update transaction, and returning an error aborts the update.