Documentation
¶
Overview ¶
Package torm 根包中的 events 内容已迁移至 events 子包 (数据库事件类型);此处保留类型与常量别名以兼容既有引用。
Index ¶
- Constants
- Variables
- func Associate(parent, owner any) error
- func DiscardChanges(model any) error
- func Dissociate(parent any, foreignKey string) error
- func EnforceMorphMap(m map[string]any)
- func Exists(model any) bool
- func FactoryHas[P any, C any](conn *Connection, parentFactory Factory[P], childFactory Factory[C], ...) (P, []C, error)
- func Fill(model any, attrs map[string]any) error
- func Flip[K comparable](c Collection[K]) map[K]int
- func ForceFill(model any, attrs map[string]any) error
- func ForgetLoadedRelations(model any)
- func ForgetModel(model any)
- func GetChanges(model any) map[string]any
- func GetDirty(model any) map[string]any
- func GetHidden(model any) []string
- func GetOriginal(model any, keys ...string) any
- func IsClean(model any, keys ...string) bool
- func IsDirty(model any, keys ...string) bool
- func IsFillable(model any, key string) bool
- func IsGuarded(model any, key string) bool
- func IsHidden(model any, key string) bool
- func LoadedRelation(model any, name string) ([]any, bool)
- func MakeHidden(model any, keys ...string)
- func MakeVisible(model any, keys ...string)
- func MapsToSlice(slice any, opts ...SerializeOptions) ([]map[string]any, error)
- func MorphAliasOf(model any) (string, bool)
- func MorphModelForAlias(alias string) any
- func MorphToAssociate(parent, owner any, morphName string) error
- func MorphToDissociate(parent any, morphName string) error
- func Reguard()
- func RelationLoaded(model any, name string) bool
- func ResetMorphMap()
- func Seed(conn *Connection, seeders ...SeederFunc) error
- func SetDateWriteFormats(date, datetime string)
- func SetDefaultUnguarded(v bool)
- func SetDeletedAtColumn(column string)
- func SetFillable(model any, keys ...string)
- func SetGuarded(model any, keys ...string)
- func SetLoadedRelation(model any, name string, models []any)
- func SetMorphMap(m map[string]any)
- func SetTimestampColumns(created, updated string)
- func SliceToJson(slice any, opts ...SerializeOptions) (string, error)
- func SortKeys[V any](m map[string]V) []string
- func StudlyCase(s string) string
- func SyncChanges(model any)
- func SyncOriginal(model any)
- func TimestampsIgnored() bool
- func ToJson(model any, opts ...SerializeOptions) (string, error)
- func ToMap(model any, opts ...SerializeOptions) (map[string]any, error)
- func TotallyGuarded(model any) bool
- func Touches(model any, relation string) bool
- func Unguard(fn func())
- func WasChanged(model any, keys ...string) bool
- func WasRecentlyCreated(model any) bool
- func WithoutTimestamps(fn func())
- type AppendedLengthAware
- type AppendedSimple
- type BelongsTo
- type BelongsToMany
- func (r BelongsToMany) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
- func (r BelongsToMany) OrWherePivot(column, operator string, value any) BelongsToMany
- func (r BelongsToMany) OrWherePivotBetween(column string, values []any) BelongsToMany
- func (r BelongsToMany) OrWherePivotIn(column string, values []any) BelongsToMany
- func (r BelongsToMany) OrWherePivotNotBetween(column string, values []any) BelongsToMany
- func (r BelongsToMany) OrWherePivotNotIn(column string, values []any) BelongsToMany
- func (r BelongsToMany) OrWherePivotNotNull(column string) BelongsToMany
- func (r BelongsToMany) OrWherePivotNull(column string) BelongsToMany
- func (r BelongsToMany) OrderByPivot(column string, direction ...string) BelongsToMany
- func (r BelongsToMany) WherePivot(column, operator string, value any) BelongsToMany
- func (r BelongsToMany) WherePivotBetween(column string, values []any) BelongsToMany
- func (r BelongsToMany) WherePivotIn(column string, values []any) BelongsToMany
- func (r BelongsToMany) WherePivotNotBetween(column string, values []any) BelongsToMany
- func (r BelongsToMany) WherePivotNotIn(column string, values []any) BelongsToMany
- func (r BelongsToMany) WherePivotNotNull(column string) BelongsToMany
- func (r BelongsToMany) WherePivotNull(column string) BelongsToMany
- func (r BelongsToMany) WithPivot(columns ...string) BelongsToMany
- func (r BelongsToMany) WithPivotValue(column string, value any) BelongsToMany
- func (r BelongsToMany) WithTimestamps() BelongsToMany
- type Builder
- func (b *Builder) AddBinding(value interface{}, segment string)
- func (b *Builder) AddSelect(columns ...interface{}) *Builder
- func (b *Builder) AddWhereExistsQuery(sub *Builder, boolean string, not bool) *Builder
- func (b *Builder) AfterQuery(callback func(any) any) *Builder
- func (b *Builder) Aggregate(function string, columns []interface{}, dest ...interface{}) error
- func (b *Builder) Average(columns string, dest ...interface{}) error
- func (b *Builder) Avg(columns string, dest ...interface{}) error
- func (b *Builder) BeforeQuery(callback func(*Builder)) *Builder
- func (b *Builder) BuilderAddBinding(value interface{}, segment string)
- func (b *Builder) Chunk(perPage uint64, makeDest func() any, callback func(page any) (bool, error)) error
- func (b *Builder) ChunkById(perPage uint64, makeDest func() any, callback func(page any) (bool, error), ...) error
- func (b *Builder) ChunkByIdDesc(perPage uint64, makeDest func() any, callback func(page any) (bool, error), ...) error
- func (b *Builder) Clone() *Builder
- func (b *Builder) CloneWithout(properties ...string) *Builder
- func (b *Builder) CloneWithoutBindings(except ...string) *Builder
- func (b *Builder) Count(dest ...interface{}) error
- func (b *Builder) CreateOrFirst(model interface{}, attributes map[string]interface{}, ...) error
- func (b *Builder) CrossJoin(table interface{}, first interface{}, args ...interface{}) *Builder
- func (b *Builder) CrossJoinSub(q interface{}, as string) *Builder
- func (b *Builder) Cursor() (iter.Seq2[map[string]any, error], error)
- func (b *Builder) CursorPaginate(dest any, perPage int64, cursor ...*Cursor) (*CursorPaginator, error)
- func (b *Builder) DD()
- func (b *Builder) DDRawSql() *Builder
- func (b *Builder) Decrement(column string, amount ...interface{}) (int64, error)
- func (b *Builder) DecrementEach(columns map[string]float64, extra map[string]interface{}) (int64, error)
- func (b *Builder) Delete(args ...interface{}) (int64, error)
- func (b *Builder) Distinct(args ...interface{}) *Builder
- func (b *Builder) DoesntExist() (bool, error)
- func (b *Builder) DoesntExistOr(callback func() error) (bool, error)
- func (b *Builder) DoesntHave(rel Relation) *Builder
- func (b *Builder) Dump() *Builder
- func (b *Builder) DumpRawSql() *Builder
- func (b *Builder) Each(makeDest func() any, callback func(item any) (bool, error)) error
- func (b *Builder) EachById(makeDest func() any, callback func(item any) (bool, error), column ...string) error
- func (b *Builder) Exists() (bool, error)
- func (b *Builder) ExistsOr(callback func() error) (bool, error)
- func (b *Builder) Explain() ([]map[string]any, error)
- func (b *Builder) Find(id interface{}, dest interface{}, columns ...interface{}) error
- func (b *Builder) FindMany(ids interface{}, dest interface{}, columns ...interface{}) error
- func (b *Builder) FindOr(id interface{}, dest interface{}, fallback func() error, ...) error
- func (b *Builder) FindOrFail(id interface{}, dest interface{}, columns ...interface{}) error
- func (b *Builder) FindOrNew(id interface{}, dest interface{}, columns ...interface{}) error
- func (b *Builder) First(dest interface{}, columns ...interface{}) error
- func (b *Builder) FirstOr(dest interface{}, fallback func() error, columns ...interface{}) error
- func (b *Builder) FirstOrCreate(model interface{}, attributes map[string]interface{}, ...) error
- func (b *Builder) FirstOrFail(dest interface{}, columns ...interface{}) error
- func (b *Builder) FirstOrNew(model interface{}, attributes map[string]interface{}, ...) error
- func (b *Builder) ForPage(page, perPage uint64) *Builder
- func (b *Builder) ForPageAfterId(perPage uint64, lastId interface{}, column ...string) *Builder
- func (b *Builder) ForPageBeforeId(perPage uint64, lastId interface{}, column ...string) *Builder
- func (b *Builder) ForceDelete() (int64, error)
- func (b *Builder) ForceIndex(index string) *Builder
- func (b *Builder) From(table interface{}) *Builder
- func (b *Builder) FromRaw(sql interface{}) *Builder
- func (b *Builder) FromSub(q interface{}, as string) *Builder
- func (b *Builder) Get(dest interface{}, columns ...interface{}) error
- func (b *Builder) GetBindings() []interface{}
- func (b *Builder) GetConnection() *Connection
- func (b *Builder) GetCountForPagination(columns ...string) (int64, error)
- func (b *Builder) GetGrammar() grammar.Grammar
- func (b *Builder) GetRawBindings() map[string][]interface{}
- func (b *Builder) GroupBy(groups ...interface{}) *Builder
- func (b *Builder) GroupByRaw(sql string, bindings ...interface{}) *Builder
- func (b *Builder) GroupLimit(value int, column string) *Builder
- func (b *Builder) Has(rel Relation, args ...any) *Builder
- func (b *Builder) Having(column interface{}, args ...interface{}) *Builder
- func (b *Builder) HavingBetween(column interface{}, values []interface{}) *Builder
- func (b *Builder) HavingNested(callback func(*Builder), boolean ...string) *Builder
- func (b *Builder) HavingNotBetween(column interface{}, values []interface{}) *Builder
- func (b *Builder) HavingNotNull(columns interface{}, args ...interface{}) *Builder
- func (b *Builder) HavingNull(columns interface{}, args ...interface{}) *Builder
- func (b *Builder) HavingRaw(sql interface{}, bindings ...interface{}) *Builder
- func (b *Builder) IgnoreIndex(index string) *Builder
- func (b *Builder) Implode(column string, glue string) (string, error)
- func (b *Builder) InOrderOf(column interface{}, values []interface{}) *Builder
- func (b *Builder) InRandomOrder(seed ...interface{}) *Builder
- func (b *Builder) Increment(column string, amount ...interface{}) (int64, error)
- func (b *Builder) IncrementEach(columns map[string]float64, extra map[string]interface{}) (int64, error)
- func (b *Builder) IncrementOrCreate(model interface{}, attributes map[string]interface{}, column string, ...) error
- func (b *Builder) Insert(value interface{}) (int64, int64, error)
- func (b *Builder) InsertGetId(value interface{}, sequence ...string) (int64, error)
- func (b *Builder) InsertOrIgnore(values []interface{}) (int64, error)
- func (b *Builder) InsertOrIgnoreReturning(values []interface{}, returning []string, uniqueBy ...[]string) ([]map[string]any, error)
- func (b *Builder) InsertOrIgnoreUsing(columns []string, q interface{}) (int64, error)
- func (b *Builder) InsertUsing(columns []string, q interface{}) (int64, error)
- func (b *Builder) Inserts(values []interface{}) (int64, int64, error)
- func (b *Builder) Join(table interface{}, first interface{}, args ...interface{}) *Builder
- func (b *Builder) JoinLateral(q interface{}, as string, typeStr ...string) *Builder
- func (b *Builder) JoinSub(q interface{}, as string, first, operator, second interface{}) *Builder
- func (b *Builder) JoinWhere(table interface{}, first string, operator string, second interface{}) *Builder
- func (b *Builder) Latest(column ...string) *Builder
- func (b *Builder) Lazy(perPage uint64) (iter.Seq2[map[string]any, error], error)
- func (b *Builder) LazyById(perPage uint64, column ...string) (iter.Seq2[map[string]any, error], error)
- func (b *Builder) LazyByIdDesc(perPage uint64, column ...string) (iter.Seq2[map[string]any, error], error)
- func (b *Builder) LeftJoin(table interface{}, first interface{}, args ...interface{}) *Builder
- func (b *Builder) LeftJoinLateral(q interface{}, as string) *Builder
- func (b *Builder) LeftJoinSub(q interface{}, as string, first, operator, second interface{}) *Builder
- func (b *Builder) LeftJoinWhere(table interface{}, first string, operator string, second interface{}) *Builder
- func (b *Builder) Limit(value uint64) *Builder
- func (b *Builder) Lock(value interface{}) *Builder
- func (b *Builder) LockForUpdate() *Builder
- func (b *Builder) Max(columns string, dest ...interface{}) error
- func (b *Builder) MergeBindings(q *Builder)
- func (b *Builder) MergeWheres(wheres []*query.Where, bindings []interface{}) *Builder
- func (b *Builder) Min(columns string, dest ...interface{}) error
- func (b *Builder) MorphToConstrain(name string, rel MorphTo, constraints ...func(*Builder)) *Builder
- func (b *Builder) MorphToOnlyTrashed(name string, rel MorphTo) *Builder
- func (b *Builder) MorphToWithCount(name string, rel MorphTo, perType map[string][]MorphCountSpec) *Builder
- func (b *Builder) MorphToWithTrashed(name string, rel MorphTo) *Builder
- func (b *Builder) MorphToWithoutTrashed(name string, rel MorphTo) *Builder
- func (b *Builder) MorphWith(name string, rel MorphTo, perType map[string]func(*Builder)) *Builder
- func (b *Builder) Offset(value uint64) *Builder
- func (b *Builder) Oldest(column ...string) *Builder
- func (b *Builder) On(first interface{}, args ...interface{}) *Builder
- func (b *Builder) OnlyTrashed() *Builder
- func (b *Builder) OrHas(rel Relation) *Builder
- func (b *Builder) OrHaving(column interface{}, args ...interface{}) *Builder
- func (b *Builder) OrHavingBetween(column interface{}, values []interface{}) *Builder
- func (b *Builder) OrHavingNested(callback func(*Builder)) *Builder
- func (b *Builder) OrHavingNotBetween(column interface{}, values []interface{}) *Builder
- func (b *Builder) OrHavingNotNull(columns interface{}) *Builder
- func (b *Builder) OrHavingNull(columns interface{}) *Builder
- func (b *Builder) OrHavingRaw(sql interface{}, bindings ...interface{}) *Builder
- func (b *Builder) OrOn(first interface{}, args ...interface{}) *Builder
- func (b *Builder) OrWhere(column interface{}, args ...interface{}) *Builder
- func (b *Builder) OrWhereAll(columns []interface{}, operator string, value interface{}) *Builder
- func (b *Builder) OrWhereAny(columns []interface{}, operator string, value interface{}) *Builder
- func (b *Builder) OrWhereBetween(column interface{}, values []interface{}) *Builder
- func (b *Builder) OrWhereBetweenColumns(column interface{}, values []interface{}) *Builder
- func (b *Builder) OrWhereColumn(first interface{}, args ...interface{}) *Builder
- func (b *Builder) OrWhereDate(column interface{}, args ...interface{}) *Builder
- func (b *Builder) OrWhereDay(column interface{}, args ...interface{}) *Builder
- func (b *Builder) OrWhereDoesntHave(rel Relation, constraints func(*Builder)) *Builder
- func (b *Builder) OrWhereExists(q interface{}) *Builder
- func (b *Builder) OrWhereExpression(condition interface{}) *Builder
- func (b *Builder) OrWhereFullText(columns interface{}, value interface{}, options ...map[string]interface{}) *Builder
- func (b *Builder) OrWhereHas(rel Relation, constraints func(*Builder)) *Builder
- func (b *Builder) OrWhereHasMorph(rel MorphMany, types []string, constraints ...func(*Builder)) *Builder
- func (b *Builder) OrWhereIn(column interface{}, values interface{}) *Builder
- func (b *Builder) OrWhereIntegerInRaw(column interface{}, values []interface{}) *Builder
- func (b *Builder) OrWhereIntegerNotInRaw(column interface{}, values []interface{}) *Builder
- func (b *Builder) OrWhereJsonContains(column interface{}, value interface{}) *Builder
- func (b *Builder) OrWhereJsonContainsKey(column interface{}) *Builder
- func (b *Builder) OrWhereJsonDoesntContain(column interface{}, value interface{}) *Builder
- func (b *Builder) OrWhereJsonDoesntContainKey(column interface{}) *Builder
- func (b *Builder) OrWhereJsonDoesntHaveLength(column interface{}, args ...interface{}) *Builder
- func (b *Builder) OrWhereJsonDoesntOverlap(column interface{}, value interface{}) *Builder
- func (b *Builder) OrWhereJsonLength(column interface{}, args ...interface{}) *Builder
- func (b *Builder) OrWhereJsonOverlaps(column interface{}, value interface{}) *Builder
- func (b *Builder) OrWhereKey(id interface{}) *Builder
- func (b *Builder) OrWhereKeyNot(id interface{}) *Builder
- func (b *Builder) OrWhereLike(column interface{}, value interface{}, caseSensitive bool) *Builder
- func (b *Builder) OrWhereMonth(column interface{}, args ...interface{}) *Builder
- func (b *Builder) OrWhereMorphedTo(morphName string, target any) *Builder
- func (b *Builder) OrWhereNested(callback func(*Builder)) *Builder
- func (b *Builder) OrWhereNone(columns []interface{}, operator string, value interface{}) *Builder
- func (b *Builder) OrWhereNot(column interface{}, args ...interface{}) *Builder
- func (b *Builder) OrWhereNotBetween(column interface{}, values []interface{}) *Builder
- func (b *Builder) OrWhereNotBetweenColumns(column interface{}, values []interface{}) *Builder
- func (b *Builder) OrWhereNotExists(q interface{}) *Builder
- func (b *Builder) OrWhereNotIn(column interface{}, values interface{}) *Builder
- func (b *Builder) OrWhereNotLike(column interface{}, value interface{}, caseSensitive bool) *Builder
- func (b *Builder) OrWhereNotNull(columns interface{}) *Builder
- func (b *Builder) OrWhereNull(columns interface{}) *Builder
- func (b *Builder) OrWhereNullSafeEquals(column interface{}, value interface{}) *Builder
- func (b *Builder) OrWhereRaw(sql interface{}, bindings ...interface{}) *Builder
- func (b *Builder) OrWhereRowValues(columns []interface{}, operator string, values []interface{}) *Builder
- func (b *Builder) OrWhereTime(column interface{}, args ...interface{}) *Builder
- func (b *Builder) OrWhereValueBetween(value interface{}, columns []interface{}) *Builder
- func (b *Builder) OrWhereValueNotBetween(value interface{}, columns []interface{}) *Builder
- func (b *Builder) OrWhereYear(column interface{}, args ...interface{}) *Builder
- func (b *Builder) OrderBy(column interface{}, direction ...string) *Builder
- func (b *Builder) OrderByDesc(column interface{}) *Builder
- func (b *Builder) OrderByRaw(sql string, bindings ...interface{}) *Builder
- func (b *Builder) Paginate(dest any, page, perPage int64) (*LengthAwarePaginator, error)
- func (b *Builder) Pluck(column string, dest interface{}) error
- func (b *Builder) RawValue(expression string) (any, error)
- func (b *Builder) Reorder(column ...interface{}) *Builder
- func (b *Builder) ReorderDesc(column interface{}) *Builder
- func (b *Builder) RightJoin(table interface{}, first interface{}, args ...interface{}) *Builder
- func (b *Builder) RightJoinSub(q interface{}, as string, first, operator, second interface{}) *Builder
- func (b *Builder) RightJoinWhere(table interface{}, first string, operator string, second interface{}) *Builder
- func (b *Builder) Scan(dest ...interface{}) error
- func (b *Builder) Select(columns ...interface{}) *Builder
- func (b *Builder) SelectRaw(sql string, bindings ...interface{}) *Builder
- func (b *Builder) SelectSub(q interface{}, as string) *Builder
- func (b *Builder) SetAggregate(function string, columns []interface{}) *Builder
- func (b *Builder) SetBindings(bindings []interface{}, segment string)
- func (b *Builder) SharedLock() *Builder
- func (b *Builder) SimplePaginate(dest any, page, perPage int64) (*SimplePaginator, error)
- func (b *Builder) Skip(value uint64) *Builder
- func (b *Builder) Sole(dest interface{}, columns ...interface{}) error
- func (b *Builder) SoleValue(column string) (any, error)
- func (b *Builder) StraightJoin(table interface{}, first string, operator string, second interface{}) *Builder
- func (b *Builder) StraightJoinSub(q interface{}, as string, first, operator, second interface{}) *Builder
- func (b *Builder) StraightJoinWhere(table interface{}, first string, operator string, second interface{}) *Builder
- func (b *Builder) Sum(columns string, dest ...interface{}) error
- func (b *Builder) Take(value uint64) *Builder
- func (b *Builder) Timeout(seconds int64) *Builder
- func (b *Builder) ToRawSql() string
- func (b *Builder) ToSql() string
- func (b *Builder) Touch(columns ...string) (int64, error)
- func (b *Builder) Truncate() error
- func (b *Builder) Union(q interface{}) *Builder
- func (b *Builder) UnionAll(q interface{}) *Builder
- func (b *Builder) Unless(condition bool, callback func(*Builder), defaultCallback ...func(*Builder)) *Builder
- func (b *Builder) Update(value map[string]interface{}) (int64, error)
- func (b *Builder) UpdateFrom(value map[string]interface{}) (int64, error)
- func (b *Builder) UpdateOrCreate(model interface{}, attributes, values map[string]interface{}) error
- func (b *Builder) UpdateOrInsert(attributes, value map[string]interface{}) (bool, error)
- func (b *Builder) Upsert(values []interface{}, uniqueBy, update []string) (int64, error)
- func (b *Builder) UseIndex(index string) *Builder
- func (b *Builder) UseWritePdo() *Builder
- func (b *Builder) Value(column string) (any, error)
- func (b *Builder) When(condition bool, callback func(*Builder), defaultCallback ...func(*Builder)) *Builder
- func (b *Builder) Where(column interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereAll(columns []interface{}, operator string, value interface{}, boolean ...string) *Builder
- func (b *Builder) WhereAny(columns []interface{}, operator string, value interface{}, boolean ...string) *Builder
- func (b *Builder) WhereBelongsTo(parent any, foreignKey ...string) *Builder
- func (b *Builder) WhereBetween(column interface{}, values []interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereBetweenColumns(column interface{}, values []interface{}) *Builder
- func (b *Builder) WhereColumn(first interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereDate(column interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereDay(column interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereDoesntHave(rel Relation, constraints func(*Builder)) *Builder
- func (b *Builder) WhereExists(q interface{}) *Builder
- func (b *Builder) WhereExpression(condition interface{}, boolean ...string) *Builder
- func (b *Builder) WhereFullText(columns interface{}, value interface{}, options ...map[string]interface{}) *Builder
- func (b *Builder) WhereHas(rel Relation, constraints func(*Builder)) *Builder
- func (b *Builder) WhereHasMorph(rel MorphMany, types []string, constraints ...func(*Builder)) *Builder
- func (b *Builder) WhereIn(column interface{}, values interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereIntegerInRaw(column interface{}, values []interface{}) *Builder
- func (b *Builder) WhereIntegerNotInRaw(column interface{}, values []interface{}) *Builder
- func (b *Builder) WhereJsonContains(column interface{}, value interface{}) *Builder
- func (b *Builder) WhereJsonContainsKey(column interface{}) *Builder
- func (b *Builder) WhereJsonDoesntContain(column interface{}, value interface{}) *Builder
- func (b *Builder) WhereJsonDoesntContainKey(column interface{}) *Builder
- func (b *Builder) WhereJsonDoesntHaveLength(column interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereJsonDoesntOverlap(column interface{}, value interface{}) *Builder
- func (b *Builder) WhereJsonLength(column interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereJsonOverlaps(column interface{}, value interface{}) *Builder
- func (b *Builder) WhereKey(id interface{}) *Builder
- func (b *Builder) WhereKeyNot(id interface{}) *Builder
- func (b *Builder) WhereLike(column interface{}, value interface{}, caseSensitive bool) *Builder
- func (b *Builder) WhereMonth(column interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereMorphedTo(morphName string, target any) *Builder
- func (b *Builder) WhereNested(callback func(*Builder), boolean ...string) *Builder
- func (b *Builder) WhereNone(columns []interface{}, operator string, value interface{}, boolean ...string) *Builder
- func (b *Builder) WhereNot(column interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereNotBetween(column interface{}, values []interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereNotBetweenColumns(column interface{}, values []interface{}) *Builder
- func (b *Builder) WhereNotExists(q interface{}) *Builder
- func (b *Builder) WhereNotIn(column interface{}, values interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereNotLike(column interface{}, value interface{}, caseSensitive bool) *Builder
- func (b *Builder) WhereNotNull(columns interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereNull(columns interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereNullSafeEquals(column interface{}, value interface{}) *Builder
- func (b *Builder) WhereRaw(sql interface{}, bindings ...interface{}) *Builder
- func (b *Builder) WhereRowValues(columns []interface{}, operator string, values []interface{}) *Builder
- func (b *Builder) WhereTime(column interface{}, args ...interface{}) *Builder
- func (b *Builder) WhereValueBetween(value interface{}, columns []interface{}) *Builder
- func (b *Builder) WhereValueNotBetween(value interface{}, columns []interface{}) *Builder
- func (b *Builder) WhereYear(column interface{}, args ...interface{}) *Builder
- func (b *Builder) With(name string, rel Relation) *Builder
- func (b *Builder) WithAggregate(name string, rel Relation, function, column string, alias ...string) *Builder
- func (b *Builder) WithAvg(name string, rel Relation, column string, alias ...string) *Builder
- func (b *Builder) WithConstraints(name string, rel Relation, constraints ...func(*Builder)) *Builder
- func (b *Builder) WithCount(name string, rel Relation, rest ...any) *Builder
- func (b *Builder) WithExists(name string, rel Relation, alias ...string) *Builder
- func (b *Builder) WithExpression(name string, q interface{}, columns ...string) *Builder
- func (b *Builder) WithLimit(name string, rel Relation, limit int64, constraints ...func(*Builder)) *Builder
- func (b *Builder) WithMax(name string, rel Relation, column string, alias ...string) *Builder
- func (b *Builder) WithMin(name string, rel Relation, column string, alias ...string) *Builder
- func (b *Builder) WithRecursiveExpression(name string, q interface{}, columns ...string) *Builder
- func (b *Builder) WithSum(name string, rel Relation, column string, alias ...string) *Builder
- func (b *Builder) WithTrashed() *Builder
- func (b *Builder) WithoutTrashed() *Builder
- type Collection
- func (c Collection[T]) Average(fields ...string) float64
- func (c Collection[T]) Chunk(size int) [][]T
- func (c Collection[T]) Clone() Collection[T]
- func (c Collection[T]) Contains(pred func(T) bool) bool
- func (c Collection[T]) ContainsValue(want T) bool
- func (c Collection[T]) ContainsWhere(field string, args ...any) bool
- func (c Collection[T]) CountBy(keyFn func(T) string) map[string]int
- func (c Collection[T]) CountWhere(pred func(T) bool) int
- func (c Collection[T]) CrossJoin[U any](other []U) []ZipPair[T, U]
- func (c Collection[T]) Diff(other Collection[T]) Collection[T]
- func (c Collection[T]) DoesntContain(pred func(T) bool) bool
- func (c Collection[T]) DoesntContainWhere(field string, args ...any) bool
- func (c Collection[T]) Duplicates() Collection[T]
- func (c Collection[T]) Each(fn func(item T, index int) bool)
- func (c Collection[T]) Every(pred func(T) bool) bool
- func (c Collection[T]) Except(keys ...string) []map[string]any
- func (c Collection[T]) Filter(pred func(T) bool) Collection[T]
- func (c Collection[T]) FilterBoth(pred func(item T, index int) bool) Collection[T]
- func (c Collection[T]) Find(id any) (T, bool)
- func (c Collection[T]) FindOrFail(id any) (T, error)
- func (c Collection[T]) First(pred func(T) bool) (T, bool)
- func (c Collection[T]) FirstWhere(field string, args ...any) (T, bool)
- func (c Collection[T]) Flatten(depth ...int) Collection[any]
- func (c Collection[T]) Forget(indices ...int) Collection[T]
- func (c Collection[T]) Fresh(conn *Connection) (Collection[T], error)
- func (c Collection[T]) GetDictionary() map[string]T
- func (c Collection[T]) GetVisible() ([]string, error)
- func (c Collection[T]) GroupBy(keyFn func(T) string) map[string][]T
- func (c Collection[T]) Implode(glue string, fields ...string) string
- func (c Collection[T]) Intersect(other Collection[T]) Collection[T]
- func (c Collection[T]) IsEmpty() bool
- func (c Collection[T]) IsNotEmpty() bool
- func (c Collection[T]) KeyBy(keyFn func(T) string) map[string]T
- func (c Collection[T]) Keys() []int
- func (c Collection[T]) Last(pred func(T) bool) (T, bool)
- func (c Collection[T]) Len() int
- func (c Collection[T]) MakeHidden(keys ...string) (Collection[T], error)
- func (c Collection[T]) MakeVisible(keys ...string) (Collection[T], error)
- func (c Collection[T]) Map[U any](fn func(T) U) []U
- func (c Collection[T]) MapWithKeys[K comparable, V any](fn func(T) (K, V)) map[K]V
- func (c Collection[T]) Max(fields ...string) any
- func (c Collection[T]) Median(fields ...string) float64
- func (c Collection[T]) Merge(other Collection[T]) Collection[T]
- func (c Collection[T]) MergeHidden(keys ...string) (Collection[T], error)
- func (c Collection[T]) Min(fields ...string) any
- func (c Collection[T]) Mode() (T, bool)
- func (c Collection[T]) ModelKeys() []any
- func (c Collection[T]) Only(keys ...string) []map[string]any
- func (c Collection[T]) Pad(size int, def T) Collection[T]
- func (c Collection[T]) Partition(pred func(T) bool) (Collection[T], Collection[T])
- func (c Collection[T]) Pluck(field string) []any
- func (c Collection[T]) Pop() (T, Collection[T], bool)
- func (c Collection[T]) Pull(index int) (T, Collection[T], bool)
- func (c Collection[T]) Push(item T) Collection[T]
- func (c Collection[T]) Random(n int) Collection[T]
- func (c Collection[T]) Reduce[U any](fn func(acc U, item T) U, initial U) U
- func (c Collection[T]) Reject(pred func(T) bool) Collection[T]
- func (c Collection[T]) Reverse() Collection[T]
- func (c Collection[T]) SetHidden(keys ...string) (Collection[T], error)
- func (c Collection[T]) Shuffle() Collection[T]
- func (c Collection[T]) Skip(n int) Collection[T]
- func (c Collection[T]) Slice() []T
- func (c Collection[T]) SliceRange(offset, length int) Collection[T]
- func (c Collection[T]) Some(pred func(T) bool) bool
- func (c Collection[T]) SortBy(less func(a, b T) bool) Collection[T]
- func (c Collection[T]) SortByDesc(less func(a, b T) bool) Collection[T]
- func (c Collection[T]) Split(n int) [][]T
- func (c Collection[T]) Sum(fields ...string) float64
- func (c Collection[T]) Take(n int) Collection[T]
- func (c Collection[T]) TakeUntil(pred func(T) bool) Collection[T]
- func (c Collection[T]) Tap(fn func(Collection[T])) Collection[T]
- func (c Collection[T]) ToJson() (string, error)
- func (c Collection[T]) ToQuery(conn *Connection) (*Builder, error)
- func (c Collection[T]) Union(other Collection[T]) Collection[T]
- func (c Collection[T]) Unique() Collection[T]
- func (c Collection[T]) UniqueBy(key func(T) any) Collection[T]
- func (c Collection[T]) Unless(cond bool, fn func(Collection[T]) Collection[T]) Collection[T]
- func (c Collection[T]) When(cond bool, fn func(Collection[T]) Collection[T]) Collection[T]
- func (c Collection[T]) Zip[U any](other []U) []ZipPair[T, U]
- type Config
- type Connection
- func (c *Connection) AddObserver(model any, o *Observer)
- func (c *Connection) AfterCommit(fn func())
- func (c *Connection) AfterRollBack(fn func())
- func (c *Connection) Attach(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) error
- func (c *Connection) AttachOrFail(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any)
- func (c *Connection) BeforeExecuting(fn func(query string, bindings []any))
- func (c *Connection) BeforeStartingTransaction(fn func())
- func (c *Connection) BeginTransaction() error
- func (c *Connection) Commit() error
- func (c *Connection) Create(model interface{}) error
- func (c *Connection) CreateManyQuietly(model any, rows []map[string]any) error
- func (c *Connection) CreateOrFirst(model interface{}, attributes map[string]interface{}, ...) error
- func (c *Connection) CreateOrRestore(model interface{}, attributes map[string]interface{}, ...) error
- func (c *Connection) CreateQuietly(model any) error
- func (c *Connection) CursorQuery(query string, bindings []interface{}, forceWrite bool) (iter.Seq2[map[string]any, error], error)
- func (c *Connection) Decrement(model any, column string, amount ...any) error
- func (c *Connection) DecrementEach(model any, columns map[string]int64, extra ...map[string]any) error
- func (c *Connection) Delete(query string, args ...interface{}) (int64, error)
- func (c *Connection) DeleteModel(model interface{}) error
- func (c *Connection) DeleteOrFail(model any) error
- func (c *Connection) DeleteQuietly(model any) error
- func (c *Connection) Destroy(model interface{}) error
- func (c *Connection) DestroyByIDs(model interface{}, ids ...interface{}) (int, error)
- func (c *Connection) Detach(parent any, rel PivotRelation, ids ...any) (int64, error)
- func (c *Connection) DetachOrFail(parent any, rel PivotRelation, ids ...any) int64
- func (c *Connection) DisableQueryLog()
- func (c *Connection) Driver() string
- func (c *Connection) Dsn() string
- func (c *Connection) EnableQueryLog()
- func (c *Connection) Escape(value any, binary ...bool) (string, error)
- func (c *Connection) FirstOrCreate(model interface{}, attributes map[string]interface{}, ...) error
- func (c *Connection) FirstOrNew(model interface{}, attributes map[string]interface{}, ...) error
- func (c *Connection) FlushQueryLog()
- func (c *Connection) ForceDelete(model interface{}) error
- func (c *Connection) ForceDeleteQuietly(model any) error
- func (c *Connection) ForgetRecordModificationState()
- func (c *Connection) Fresh(model any) (any, error)
- func (c *Connection) GetConfig() Config
- func (c *Connection) GetDatabaseName() string
- func (c *Connection) GetName() string
- func (c *Connection) GetQueryGrammar() grammar.Grammar
- func (c *Connection) GetQueryLog() []QueryExecuted
- func (c *Connection) GetRawQueryLog() []RawQueryLog
- func (c *Connection) GetSchemaGrammar() grammar.SchemaGrammar
- func (c *Connection) HasModifiedRecords() bool
- func (c *Connection) Increment(model any, column string, amount ...any) error
- func (c *Connection) IncrementEach(model any, columns map[string]int64, extra ...map[string]any) error
- func (c *Connection) Insert(query string, args ...interface{}) (int64, int64, error)
- func (c *Connection) InsertGetId(query string, args ...interface{}) (int64, error)
- func (c *Connection) IsMaria() bool
- func (c *Connection) Listen(fn func(QueryExecuted))
- func (c *Connection) Load(model any, name string, rel Relation, constraints ...func(*Builder)) error
- func (c *Connection) LoadAggregate(model any, name string, rel Relation, function, column string, rest ...any) error
- func (c *Connection) LoadAvg(model any, name string, rel Relation, column string, rest ...any) error
- func (c *Connection) LoadCount(model any, name string, rel Relation, rest ...any) error
- func (c *Connection) LoadExists(model any, name string, rel Relation, rest ...any) error
- func (c *Connection) LoadMany(model any, rels map[string]Relation) error
- func (c *Connection) LoadMax(model any, name string, rel Relation, column string, rest ...any) error
- func (c *Connection) LoadMin(model any, name string, rel Relation, column string, rest ...any) error
- func (c *Connection) LoadMissing(model any, name string, rel Relation, constraints ...func(*Builder)) error
- func (c *Connection) LoadMorph(model any, name string, rel Relation) error
- func (c *Connection) LoadMorphCount(model any, name string, rel Relation) error
- func (c *Connection) LoadSum(model any, name string, rel Relation, column string, rest ...any) error
- func (c *Connection) Model(model interface{}) *Builder
- func (c *Connection) Observe(model any, o *Observer)
- func (c *Connection) OnQuery(fn func(QueryExecuted))
- func (c *Connection) Pretend(fn func(*Connection)) []QueryExecuted
- func (c *Connection) Push(model any) error
- func (c *Connection) PushQuietly(model any) error
- func (c *Connection) Query() *Builder
- func (c *Connection) Raw(value string) grammar.Expression
- func (c *Connection) RecordsHaveBeenModified(value bool)
- func (c *Connection) Refresh(model any) error
- func (c *Connection) RelationCreate(parent any, rel Relation, attributes map[string]any) (any, error)
- func (c *Connection) RelationFind(parent any, rel Relation, id any) (any, error)
- func (c *Connection) RelationFirst(parent any, rel Relation, constraints ...func(*Builder)) (any, error)
- func (c *Connection) RelationFirstOr(parent any, rel Relation, fallback func() (any, error), ...) (any, error)
- func (c *Connection) RelationFirstOrCreate(parent any, rel Relation, attributes map[string]any, values ...map[string]any) (any, error)
- func (c *Connection) RelationFirstOrFail(parent any, rel Relation, constraints ...func(*Builder)) any
- func (c *Connection) RelationSave(parent any, rel Relation, related any) error
- func (c *Connection) RelationSole(parent any, rel Relation, constraints ...func(*Builder)) (any, error)
- func (c *Connection) RelationUpdateOrCreate(parent any, rel Relation, attributes, values map[string]any) (any, error)
- func (c *Connection) Replicate(dst, src any) error
- func (c *Connection) ResetTotalQueryDuration()
- func (c *Connection) Restore(model interface{}) error
- func (c *Connection) RestoreOrCreate(model interface{}, attributes map[string]interface{}, ...) error
- func (c *Connection) RestoreQuietly(model any) error
- func (c *Connection) RollBack() error
- func (c *Connection) RollBackToLevel(toLevel int) error
- func (c *Connection) Save(model interface{}) error
- func (c *Connection) SaveOrFail(model any) error
- func (c *Connection) SaveOrIgnore(model any) (bool, error)
- func (c *Connection) SaveQuietly(model any) error
- func (c *Connection) Scalar(query string, bindings []interface{}) (any, error)
- func (c *Connection) Scan(query string, bindings []interface{}, dest ...interface{}) error
- func (c *Connection) Schema() *SchemaBuilder
- func (c *Connection) Select(query string, bindings []interface{}, dest interface{}) error
- func (c *Connection) SelectFromWrite(query string, bindings []interface{}, dest interface{}) error
- func (c *Connection) SelectMaps(query string, bindings []interface{}) ([]map[string]any, error)
- func (c *Connection) SelectOne(query string, bindings []interface{}, dest interface{}) error
- func (c *Connection) SelectResultSets(query string, bindings []interface{}) ([][]map[string]any, error)
- func (c *Connection) ServerVersion() (string, error)
- func (c *Connection) SetConnectionName(name string)
- func (c *Connection) SetDatabaseName(name string)
- func (c *Connection) SetEventDispatcher(d events.Dispatcher)
- func (c *Connection) SetReconnector(fn func(*Connection) error)
- func (c *Connection) SetRecordModificationState(value bool)
- func (c *Connection) Statement(query string, args ...interface{}) error
- func (c *Connection) Sync(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) (*SyncResult, error)
- func (c *Connection) SyncOrFail(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) *SyncResult
- func (c *Connection) SyncWithPivotValues(parent any, rel PivotRelation, ids []any, values map[string]any, ...) (*SyncResult, error)
- func (c *Connection) SyncWithoutDetaching(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) (*SyncResult, error)
- func (c *Connection) Table(table string) *Builder
- func (c *Connection) ThreadCount() (int, error)
- func (c *Connection) Toggle(parent any, rel PivotRelation, ids []any) (*SyncResult, error)
- func (c *Connection) ToggleOrFail(parent any, rel PivotRelation, ids []any) *SyncResult
- func (c *Connection) TotalQueryDuration() float64
- func (c *Connection) Touch(model any) error
- func (c *Connection) TouchOwners(model any) error
- func (c *Connection) TouchQuietly(model any) error
- func (c *Connection) Transaction(fn func(*Connection) error, attempts ...int) error
- func (c *Connection) TransactionLevel() int
- func (c *Connection) Unobserve(model any)
- func (c *Connection) Unprepared(query string) (bool, error)
- func (c *Connection) UnsetEventDispatcher()
- func (c *Connection) Update(query string, args ...interface{}) (int64, error)
- func (c *Connection) UpdateExistingPivot(parent any, rel PivotRelation, id any, attrs map[string]any) (int64, error)
- func (c *Connection) UpdateExistingPivotOrFail(parent any, rel PivotRelation, id any, attrs map[string]any) int64
- func (c *Connection) UpdateModel(model any, attrs map[string]any) error
- func (c *Connection) UpdateOrCreate(model interface{}, attributes, values map[string]interface{}) error
- func (c *Connection) UpdateQuietly(model any, attrs map[string]any) error
- func (c *Connection) UseWriteConnectionWhenReading(value ...bool)
- func (c *Connection) WhenQueryingForLongerThan(thresholdMs int64, handler func(QueryExecuted))
- func (c *Connection) WithoutPretending(fn func() error) error
- func (c *Connection) WriteDB() *sql.DB
- type Connector
- type Cursor
- type CursorPaginator
- type Dispatcher
- type ErrInvalid
- type ErrMultiple
- type ErrNotFound
- type Error
- type ErrorKind
- type Event
- type EventBus
- type Factory
- func (f Factory[T]) AfterCreating(fn func(T)) Factory[T]
- func (f Factory[T]) AfterMaking(fn func(T)) Factory[T]
- func (f Factory[T]) Count(n int) Factory[T]
- func (f Factory[T]) Create(conn *Connection, count int) ([]T, error)
- func (f Factory[T]) CreateMany(conn *Connection) ([]T, error)
- func (f Factory[T]) CreateOne(conn *Connection) (T, error)
- func (f Factory[T]) For(parent any, foreignKey ...string) Factory[T]
- func (f Factory[T]) Make(count int) []T
- func (f Factory[T]) MakeMany() []T
- func (f Factory[T]) MakeOne() T
- func (f Factory[T]) Sequence(mutators ...func(seq int, m T)) Factory[T]
- func (f Factory[T]) SequenceAttrs(attrs ...map[string]any) Factory[T]
- func (f Factory[T]) State(name string, mutator func(T)) Factory[T]
- type FailError
- type Field
- type HasMany
- type HasManyThrough
- type HasOne
- func (r HasOne) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
- func (r HasOne) LatestOfMany(column ...string) HasOne
- func (r HasOne) OfMany(column, aggregate string) HasOne
- func (r HasOne) OldestOfMany(column ...string) HasOne
- func (r HasOne) One() HasOne
- func (r HasOne) WithDefault(fn ...func(inst any) any) HasOne
- type HasOneThrough
- type LengthAwarePaginator
- func (p LengthAwarePaginator) Appends(query map[string]string) AppendedLengthAware
- func (p LengthAwarePaginator) FirstItem() int
- func (p LengthAwarePaginator) From() int
- func (p LengthAwarePaginator) HasMorePages() bool
- func (p LengthAwarePaginator) LastItem() int
- func (p LengthAwarePaginator) PageLinks(onEachSide int) []int
- func (p LengthAwarePaginator) To() int
- func (p LengthAwarePaginator) URL(page int, query map[string]string) string
- type Listener
- type Manager
- func (m *Manager) AddConfig(name string, config Config)
- func (m *Manager) Connect(name string) (*Connection, error)
- func (m *Manager) ConnectUsing(name string, config Config, force ...bool) (*Connection, error)
- func (m *Manager) Disconnect(name string) error
- func (m *Manager) Extend(driver string, resolver func(Config) (*Connection, error))
- func (m *Manager) ForgetExtension(driver string)
- func (m *Manager) GetConnections() []string
- func (m *Manager) GetDefaultConnection() string
- func (m *Manager) Purge(name string) error
- func (m *Manager) Reconnect(name string) (*Connection, error)
- func (m *Manager) SetDefaultConnection(name string)
- func (m *Manager) SetEventDispatcher(d events.Dispatcher)
- func (m *Manager) SetReconnector(fn func(*Connection) error)
- func (m *Manager) Transaction(name string, fn func(*Connection) error, attempts ...int) error
- func (m *Manager) UsingConnection(name string, callback func() error) error
- type MassAssignmentError
- type Model
- type ModelEvent
- type MorphCountSpec
- type MorphMany
- type MorphOne
- func (r MorphOne) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
- func (r MorphOne) LatestOfMany(column ...string) MorphOne
- func (r MorphOne) OfMany(column, aggregate string) MorphOne
- func (r MorphOne) OldestOfMany(column ...string) MorphOne
- func (r MorphOne) One() MorphOne
- func (r MorphOne) WithDefault(fn ...func(inst any) any) MorphOne
- type MorphTo
- type MorphToMany
- type MorphedByMany
- type MySqlConnector
- type Observer
- type PivotRelation
- type PivotScopeCond
- type PivotSpec
- type PostgresConnector
- type QueryExecuted
- type RawQueryLog
- type Relation
- type SQLiteConnector
- type Schema
- type SchemaBuilder
- func (s *SchemaBuilder) AlterTable(table string, fn func(t *grammar.Blueprint)) error
- func (s *SchemaBuilder) Create(table string, fn func(t *grammar.Blueprint)) error
- func (s *SchemaBuilder) CreateDatabase(name string) error
- func (s *SchemaBuilder) CreateTable(table string, fn func(t *grammar.Blueprint)) error
- func (s *SchemaBuilder) DisableForeignKeyConstraints() error
- func (s *SchemaBuilder) Drop(table string) error
- func (s *SchemaBuilder) DropAllTables() error
- func (s *SchemaBuilder) DropAllTypes() error
- func (s *SchemaBuilder) DropAllViews() error
- func (s *SchemaBuilder) DropColumns(table string, columns ...string) error
- func (s *SchemaBuilder) DropDatabaseIfExists(name string) error
- func (s *SchemaBuilder) DropIfExists(table string) error
- func (s *SchemaBuilder) EnableForeignKeyConstraints() error
- func (s *SchemaBuilder) GetColumnListing(table string) ([]string, error)
- func (s *SchemaBuilder) GetColumnType(table, column string) (string, error)
- func (s *SchemaBuilder) GetColumns(table string) ([]SchemaColumn, error)
- func (s *SchemaBuilder) GetForeignKeys(table string) ([]SchemaForeignKey, error)
- func (s *SchemaBuilder) GetIndexListing(table string) ([]string, error)
- func (s *SchemaBuilder) GetIndexes(table string) ([]SchemaIndex, error)
- func (s *SchemaBuilder) GetTableListing(schema ...string) ([]string, error)
- func (s *SchemaBuilder) GetTables(schema ...string) ([]SchemaTable, error)
- func (s *SchemaBuilder) GetTypes(schema ...string) ([]SchemaType, error)
- func (s *SchemaBuilder) GetViews(schema ...string) ([]SchemaView, error)
- func (s *SchemaBuilder) HasColumn(table, column string) (bool, error)
- func (s *SchemaBuilder) HasColumns(table string, columns []string) (bool, error)
- func (s *SchemaBuilder) HasForeignKey(table string, foreignKey any) (bool, error)
- func (s *SchemaBuilder) HasIndex(table string, index any, typ ...string) (bool, error)
- func (s *SchemaBuilder) HasTable(table string) (bool, error)
- func (s *SchemaBuilder) HasView(view string) (bool, error)
- func (s *SchemaBuilder) Rename(from, to string) error
- func (s *SchemaBuilder) Statement(query string, args ...any) error
- func (s *SchemaBuilder) Table(table string, fn func(t *grammar.Blueprint)) error
- func (s *SchemaBuilder) WhenTableDoesntHaveColumn(table, column string, fn func(t *grammar.Blueprint)) error
- func (s *SchemaBuilder) WhenTableDoesntHaveIndex(table string, index any, fn func(t *grammar.Blueprint), typ ...string) error
- func (s *SchemaBuilder) WhenTableHasColumn(table, column string, fn func(t *grammar.Blueprint)) error
- func (s *SchemaBuilder) WhenTableHasIndex(table string, index any, fn func(t *grammar.Blueprint), typ ...string) error
- func (s *SchemaBuilder) WithoutForeignKeyConstraints(fn func() error) error
- type SchemaColumn
- type SchemaForeignKey
- type SchemaIndex
- type SchemaTable
- type SchemaType
- type SchemaView
- type SeederFunc
- type SerializeOptions
- type SimplePaginator
- func (p SimplePaginator) Appends(query map[string]string) AppendedSimple
- func (p SimplePaginator) FirstItem() int
- func (p SimplePaginator) From() int
- func (p SimplePaginator) HasMorePages() bool
- func (p SimplePaginator) LastItem() int
- func (p SimplePaginator) To() int
- func (p SimplePaginator) URL(page int, query map[string]string) string
- type SoftDeletes
- type SqlServerConnector
- type SyncResult
- type TableName
- type ZipPair
Constants ¶
const ( EventRetrieving = events.Retrieving EventRetrieved = events.Retrieved EventCreating = events.Creating EventCreated = events.Created EventUpdating = events.Updating EventUpdated = events.Updated EventSaving = events.Saving EventSaved = events.Saved EventDeleting = events.Deleting EventDeleted = events.Deleted EventTrashed = events.Trashed EventRestoring = events.Restoring EventRestored = events.Restored EventReplicating = events.Replicating EventForceDeleting = events.ForceDeleting EventForceDeleted = events.ForceDeleted )
模型生命周期事件名。
Variables ¶
var ErrMultipleColumnsSelected = errors.New("torm: multiple columns selected")
ErrMultipleColumnsSelected 单行查询命中多列时返回的错误 (Scalar 命中多列时抛出)。
var NewEventBus = events.NewEventBus
Functions ¶
func DiscardChanges ¶
DiscardChanges 把属性回滚到 original; 无快照的新模型清零全部字段。json 快照为序列化字符串,回滚时反序列化还原。
func Dissociate ¶
Dissociate 将 parent 的外键列置空(Go 无方法名魔法,外键列需显式给出; 不自动 save)。
func EnforceMorphMap ¶
func FactoryHas ¶
func FactoryHas[P any, C any](conn *Connection, parentFactory Factory[P], childFactory Factory[C], foreignKey string, count int) (P, []C, error)
FactoryHas 最小可用的 has 关系工厂组合(has 语义): 先用 parentFactory 创建父模型,再以 parent 主键填充 childFactory 模型的 foreignKey 外键列创建 count 个子模型;返回 (父模型, 子模型集合)。
func Flip ¶
func Flip[K comparable](c Collection[K]) map[K]int
Flip 值翻转为键:元素值 → 首次出现的下标; 重复值保留首次出现。Go 方法不能新增 comparable 约束, 以包级泛型函数提供。
func ForgetLoadedRelations ¶
func ForgetLoadedRelations(model any)
ForgetLoadedRelations 释放模型的全部关系缓存(测试与长生命周期防泄漏用)。
func ForgetModel ¶
func ForgetModel(model any)
ForgetModel 释放模型在全局状态表中的快照(对象弃用时的清理路径)。 内嵌 field.ModelStateAttr 的模型状态随实例走 GC,无需调用; 未内嵌的模型状态表以指针为键持强引用,长驻进程建议调用或改用内嵌基座。
func GetOriginal ¶
GetOriginal 返回列的 original 值;无快照时退回当前值。 不传 key 时返回整个 original map 的副本 (无 key 全量形态);无快照时退回当前属性全量快照。
func IsFillable ¶
IsFillable 判断列是否可被 Fill 赋值。 支持前缀通配(fillable tag "col_*",模式匹配)。
func LoadedRelation ¶
LoadedRelation 取惰性加载的关系结果(不存在时 ok=false)。
func MapsToSlice ¶
func MapsToSlice(slice any, opts ...SerializeOptions) ([]map[string]any, error)
MapsToSlice 把模型切片/数组序列化为 []map。
func MorphModelForAlias ¶
MorphModelForAlias 按别名解析模型零值(未知别名返回 nil)。
func MorphToAssociate ¶
MorphToAssociate 写外键与类型双列(对应 MorphTo::associate): 类型取值 = morph map 别名,未注册时回退 owner 表名。
func MorphToDissociate ¶
MorphToDissociate 同时清空 id 列与 type 列(对应 MorphTo::dissociate)。
func SetDateWriteFormats ¶
func SetDateWriteFormats(date, datetime string)
SetDateWriteFormats 覆写 cast:date / cast:datetime 的写入格式(Go 布局)。
func SetDefaultUnguarded ¶
func SetDefaultUnguarded(v bool)
SetDefaultUnguarded 修改"未声明守卫模型"的默认方向: true = 默认全可填(本库契约,默认值);false = 全守卫方向 (未声明守卫的模型完全守卫,Fill 抛错)。仅影响"既无 fillable 也无 guarded tag/注册"的模型类型。
func SetDeletedAtColumn ¶
func SetDeletedAtColumn(column string)
SetDeletedAtColumn 设置全局软删列名默认值(软删时间戳列)。
func SetFillable ¶
SetFillable 设置模型类型的可填充列(keys 为空 = 清空列表)。
func SetGuarded ¶
SetGuarded 设置模型类型的守卫列;不传 keys 等价 ["*"](全部守卫)。
func SetLoadedRelation ¶
SetLoadedRelation 把关系结果缓存到模型。
func SetTimestampColumns ¶
func SetTimestampColumns(created, updated string)
SetTimestampColumns 设置全局 created_at/updated_at 列名默认值 (覆写全局 created_at/updated_at 列名常量;空串保持默认)。 单模型可用 tag `torm:"created=col"` / `torm:"updated=col"` / `torm:"deleted=col"` 覆盖。
func SliceToJson ¶
func SliceToJson(slice any, opts ...SerializeOptions) (string, error)
SliceToJson 把模型切片序列化为 JSON 数组。
func TimestampsIgnored ¶
func TimestampsIgnored() bool
TimestampsIgnored 当前是否处于 WithoutTimestamps 作用域内。
func ToJson ¶
func ToJson(model any, opts ...SerializeOptions) (string, error)
ToJson 把模型序列化为 JSON(hidden 语义同 ToMap)。
func ToMap ¶
func ToMap(model any, opts ...SerializeOptions) (map[string]any, error)
ToMap 把模型序列化为 map: hidden(tag `torm:"hidden"` + MakeHidden + options.Hidden)列被剔除; options.Visible 非空时仅输出其交集;json cast 字段输出解码后的值。
func TotallyGuarded ¶
TotallyGuarded 判断模型是否完全守卫(无 fillable 且 guarded == ["*"])。
func WasChanged ¶
WasChanged 判断最近一次更新是否有(指定列的)实际写库变更。
func WasRecentlyCreated ¶
WasRecentlyCreated 判断模型是否由最近一次 Create 写入。
func WithoutTimestamps ¶
func WithoutTimestamps(fn func())
WithoutTimestamps 在 fn 执行期间禁用时间戳写入(Save/Create/软删均不写 created_at/updated_at;支持嵌套)。注意:作用域计数是进程级的静态 开关,作用域内不要并发执行其它模型的写入。
Types ¶
type AppendedLengthAware ¶
type AppendedLengthAware struct {
LengthAwarePaginator
// Query 经 Appends 追加的公共查询参数。
Query map[string]string
}
AppendedLengthAware 携带 Appends 查询参数的 LengthAwarePaginator 副本。
type AppendedSimple ¶
type AppendedSimple struct {
SimplePaginator
// Query 经 Appends 追加的公共查询参数。
Query map[string]string
}
AppendedSimple 携带 Appends 查询参数的 SimplePaginator 副本。
type BelongsTo ¶
type BelongsTo struct {
ForeignKey string // 本表列(默认 *_id)
OwnerKey string // 目标表键(默认 id)
Model any // 目标模型零值
// withDefault(对应 SupportsDefaultModels):关系未命中时返回空实例而非 nil;
// DefaultFn 非 nil 时以新实例调用,返回值非 nil 则使用之
HasDefault bool
DefaultFn func(inst any) any
}
BelongsTo 反向一对一:本表持有外键。
func (BelongsTo) GetResults ¶
func (r BelongsTo) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
GetResults 单父查询:按 parent 的外键取 owner(对应 BelongsTo::getResults, 未命中时 withDefault 生效返回默认实例)。
type BelongsToMany ¶
type BelongsToMany struct {
RelatedModel any // 目标模型零值(Role{})
Table string
ForeignPivotKey string // 本表在 pivot 中的键(user_id)
RelatedPivotKey string // 目标表在 pivot 中的键(role_id)
RelatedKey string // 目标表主键(id)
// pivot 读侧选项(对应 InteractsWithPivotTable / BelongsToMany 链式配置)
PivotColumns []string // WithPivot:select 附加的 pivot 列(pivot_ 前缀别名)
PivotTimestamps bool // WithTimestamps:pivot 表 created_at/updated_at
// contains filtered or unexported fields
}
BelongsToMany 多对多(经 pivot 表)。 默认命名:pivot 表 = 两表单数按字典序拼接(role_user),外键 = 表名_id。
func (BelongsToMany) GetResults ¶
func (r BelongsToMany) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
GetResults 单父查询:经 pivot 中间表取关联模型(对应 BelongsToMany::getResults)。
func (BelongsToMany) OrWherePivot ¶
func (r BelongsToMany) OrWherePivot(column, operator string, value any) BelongsToMany
OrWherePivot 作用于 pivot 表列的 or where(对应 orWherePivot)。
func (BelongsToMany) OrWherePivotBetween ¶
func (r BelongsToMany) OrWherePivotBetween(column string, values []any) BelongsToMany
OrWherePivotBetween pivot 列 between(or 布尔)。
func (BelongsToMany) OrWherePivotIn ¶
func (r BelongsToMany) OrWherePivotIn(column string, values []any) BelongsToMany
OrWherePivotIn pivot 列 in(or 布尔,对应 orWherePivotIn)。
func (BelongsToMany) OrWherePivotNotBetween ¶
func (r BelongsToMany) OrWherePivotNotBetween(column string, values []any) BelongsToMany
OrWherePivotNotBetween pivot 列 not between(or 布尔)。
func (BelongsToMany) OrWherePivotNotIn ¶
func (r BelongsToMany) OrWherePivotNotIn(column string, values []any) BelongsToMany
OrWherePivotNotIn pivot 列 not in(or 布尔)。
func (BelongsToMany) OrWherePivotNotNull ¶
func (r BelongsToMany) OrWherePivotNotNull(column string) BelongsToMany
OrWherePivotNotNull pivot 列 is not null(or 布尔)。
func (BelongsToMany) OrWherePivotNull ¶
func (r BelongsToMany) OrWherePivotNull(column string) BelongsToMany
OrWherePivotNull pivot 列 is null(or 布尔)。
func (BelongsToMany) OrderByPivot ¶
func (r BelongsToMany) OrderByPivot(column string, direction ...string) BelongsToMany
OrderByPivot 按 pivot 表列排序(对应 orderByPivot)。
func (BelongsToMany) WherePivot ¶
func (r BelongsToMany) WherePivot(column, operator string, value any) BelongsToMany
WherePivot 作用于 pivot 表列的 where(对应 wherePivot)。
func (BelongsToMany) WherePivotBetween ¶
func (r BelongsToMany) WherePivotBetween(column string, values []any) BelongsToMany
WherePivotBetween pivot 列 between(对应 wherePivotBetween,values 取前两个)。
func (BelongsToMany) WherePivotIn ¶
func (r BelongsToMany) WherePivotIn(column string, values []any) BelongsToMany
WherePivotIn 作用于 pivot 表列的 where in(对应 wherePivotIn)。
func (BelongsToMany) WherePivotNotBetween ¶
func (r BelongsToMany) WherePivotNotBetween(column string, values []any) BelongsToMany
WherePivotNotBetween pivot 列 not between(对应 wherePivotNotBetween)。
func (BelongsToMany) WherePivotNotIn ¶
func (r BelongsToMany) WherePivotNotIn(column string, values []any) BelongsToMany
WherePivotNotIn pivot 列 not in(对应 wherePivotNotIn)。
func (BelongsToMany) WherePivotNotNull ¶
func (r BelongsToMany) WherePivotNotNull(column string) BelongsToMany
WherePivotNotNull pivot 列 is not null(对应 wherePivotNotNull)。
func (BelongsToMany) WherePivotNull ¶
func (r BelongsToMany) WherePivotNull(column string) BelongsToMany
WherePivotNull pivot 列 is null(对应 wherePivotNull)。
func (BelongsToMany) WithPivot ¶
func (r BelongsToMany) WithPivot(columns ...string) BelongsToMany
WithPivot 附加 pivot 列到 select(别名带 pivot_ 前缀,对应 withPivot)。
func (BelongsToMany) WithPivotValue ¶
func (r BelongsToMany) WithPivotValue(column string, value any) BelongsToMany
WithPivotValue attach/sync 附加的每行 pivot 固定值(对应 BelongsToMany.php:494 withPivotValue($column, $value)):显式传入的 pivotAttrs 优先于固定值。
func (BelongsToMany) WithTimestamps ¶
func (r BelongsToMany) WithTimestamps() BelongsToMany
WithTimestamps pivot 表带 created_at/updated_at(对应 withTimestamps)。
type Builder ¶
type Builder struct {
Connection *Connection
Query *query.Query
Bindings map[string][]interface{}
// contains filtered or unexported fields
}
Builder 查询构建器:封装 query.Query,经 grammar 编译为方言 SQL。
func NewBuilder ¶
func NewBuilder(connection *Connection, g grammar.Grammar) *Builder
func (*Builder) AddBinding ¶
AddBinding 添加绑定(导出入口)。
func (*Builder) AddWhereExistsQuery ¶
AddWhereExistsQuery 将 exists 子查询挂为 where 条件。
func (*Builder) AfterQuery ¶
AfterQuery 注册查询执行后回调(Get 成功后应用)。
func (*Builder) Aggregate ¶
Aggregate 在克隆上执行聚合,不污染原查询: 无 unions/havings 时 cloneWithout(['columns']) + cloneWithoutBindings(['select']), 再由 setAggregate 在 groups 为空时清除 orders 与 order 段绑定。
func (*Builder) BeforeQuery ¶
BeforeQuery 注册查询执行前回调(toSql 与写入族执行前应用)。
func (*Builder) BuilderAddBinding ¶
BuilderAddBinding 添加绑定;未知段 panic。
func (*Builder) Chunk ¶
func (b *Builder) Chunk(perPage uint64, makeDest func() any, callback func(page any) (bool, error)) error
Chunk 分块处理:每块通过 makeDest 创建扫描目标(如 func() any { return &[]User{} }), 回调返回 false 提前终止。
func (*Builder) ChunkById ¶
func (b *Builder) ChunkById(perPage uint64, makeDest func() any, callback func(page any) (bool, error), column ...string) error
ChunkById 基于列游标的分块处理,避免大 offset。 makeDest 每页创建扫描目标(如 func() any { return &[]User{} });回调返回 false 提前终止。 首块 lastId=nil 走 whereNotNull(起始游标不硬编码 0, 字符串主键/负值主键同样适用)。
func (*Builder) ChunkByIdDesc ¶
func (b *Builder) ChunkByIdDesc(perPage uint64, makeDest func() any, callback func(page any) (bool, error), column ...string) error
ChunkByIdDesc 基于列游标的降序分块: 游标向更小值推进,取块内最后一行的列值(降序排列时最小)。
func (*Builder) Clone ¶
Clone 深拷贝查询状态(切片复制,嵌套 Query/Join 引用共享,与 PHP clone 语义一致)。 软删 scope 的物化状态(scopesApplied/softDelete)随 wheres 一并继承, 避免克隆链(ChunkById/lazy 翻页)重复追加约束。
func (*Builder) CloneWithout ¶
CloneWithout 克隆并清除指定属性(columns/orders/limit/offset/aggregate/distinct/unions)。
func (*Builder) CloneWithoutBindings ¶
CloneWithoutBindings 克隆并移除指定段的绑定。
func (*Builder) CreateOrFirst ¶
func (b *Builder) CreateOrFirst(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error
CreateOrFirst 先尝试创建,唯一约束冲突时回退按 attributes 查询 (转发 Connection.CreateOrFirst 的并发安全语义)。
func (*Builder) CrossJoinSub ¶
CrossJoinSub 交叉 join 子查询(无 on 条件,对应 crossJoinSub)。
func (*Builder) CursorPaginate ¶
func (b *Builder) CursorPaginate(dest any, perPage int64, cursor ...*Cursor) (*CursorPaginator, error)
CursorPaginate 游标分页: 依据 order 列生成游标条件(支持多列嵌套 or),cursor 为 "" 或 nil 表示首页。
func (*Builder) DDRawSql ¶
DDRawSql 打印内联绑定后的 SQL。 与 dd 的差异:dd 是 die-dump(打印后终止脚本); Go 侧不做 os.Exit(终止宿主进程的职责在调用方),仅打印后返回 builder。
func (*Builder) DecrementEach ¶
func (b *Builder) DecrementEach(columns map[string]float64, extra map[string]interface{}) (int64, error)
DecrementEach 按列批量递减。
func (*Builder) Delete ¶
Delete 删除;可传主键值(对应 delete($id))。 关联软删模型时编译为 update set deleted_at = now(软删宏 onDelete 语义), 并分发 deleting/trashed/deleted 事件; 无关联模型且无任何 where 条件时返回错误,拒绝整表 DELETE。
func (*Builder) DoesntExist ¶
func (*Builder) DoesntExistOr ¶
DoesntExistOr 不存在返回 true,否则执行回调。
func (*Builder) DoesntHave ¶
DoesntHave 关系不存在性约束:where not exists (...)。
func (*Builder) EachById ¶
func (b *Builder) EachById(makeDest func() any, callback func(item any) (bool, error), column ...string) error
EachById 为 ChunkById 的逐行封装。
func (*Builder) Exists ¶
Exists 存在性检查:select exists(...) as "exists"。 必须先应用模型全局 scope(软删等),否则软删模型会把已删行当作存在。
func (*Builder) Explain ¶
Explain 返回执行计划(explain + SQL)。 Explain 输出执行计划;SQLServer 不支持 "explain select" 语法,显式报错。
func (*Builder) FindOr ¶
func (b *Builder) FindOr(id interface{}, dest interface{}, fallback func() error, columns ...interface{}) error
FindOr 按主键取单行,未命中执行 fallback。
func (*Builder) FindOrFail ¶
FindOrFail 按主键取单行,未命中返回 *ErrNotFound (即记录不存在错误)。
func (*Builder) FirstOrCreate ¶
func (b *Builder) FirstOrCreate(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error
FirstOrCreate 按 attributes 查找;未命中则合并 attributes+values 创建 (转发 Connection.FirstOrCreate,保持两者语义一致)。
func (*Builder) FirstOrFail ¶
FirstOrFail 未命中返回 ErrNotFound。
func (*Builder) FirstOrNew ¶
func (b *Builder) FirstOrNew(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error
FirstOrNew 按 attributes 查找;未命中仅构造不落库(转发 Connection.FirstOrNew)。
func (*Builder) ForPageAfterId ¶
ForPageAfterId 基于列游标的分页:where column > lastId + orderBy column asc + limit 不使用 offset;lastId 为 nil 时约束列非空。
func (*Builder) ForPageBeforeId ¶
ForPageBeforeId 基于列游标向前翻页:where column < lastId + orderBy column desc + limit lastId 为 nil 时约束列非空。
func (*Builder) ForceDelete ¶
ForceDelete 硬删除:跳过软删宏,编译为裸 DELETE(绕过模型层 直接走底层 delete)。
func (*Builder) ForceIndex ¶
ForceIndex 设置索引提示(force index)。
func (*Builder) GetBindings ¶
func (b *Builder) GetBindings() []interface{}
GetBindings 按固定段顺序(select→from→join→where→groupBy→having→order→union→unionOrder)合并绑定。 GetBindings 按 grammar.BindingSegments 顺序合并绑定段("with" 居首: CTE 编译在最终 SQL 最前,其占位符最先求值)。
func (*Builder) GetConnection ¶
func (b *Builder) GetConnection() *Connection
func (*Builder) GetCountForPagination ¶
GetCountForPagination 取分页总数: 有 group/having 时包裹子查询计数,否则去除 columns/orders/limit/offset 后聚合。
func (*Builder) GetGrammar ¶
func (*Builder) GetRawBindings ¶
GetRawBindings 返回按段分组的原始绑定。
func (*Builder) GroupByRaw ¶
func (*Builder) GroupLimit ¶
GroupLimit 分组限额: value >= 0 时设置(编译为 row_number() over (partition by column) <= value, 预加载分组限额的基础入口)。
func (*Builder) Has ¶
Has 关系存在性/计数阈值(has($relation, $operator, $count) 形态): Has(rel) 等价 Has(rel, ">=", 1);Has(rel, 3) 默认操作符 >=; Has(rel, ">", 2) 自定义操作符。实现见 builder.go hasImpl。
func (*Builder) HavingBetween ¶
HavingBetween / OrHavingBetween / HavingNotBetween / OrHavingNotBetween 绑定取 flatten 后前两个。
func (*Builder) HavingNested ¶
HavingNested / OrHavingNested / addNestedHavingQuery:嵌套 having 条件组。
func (*Builder) HavingNotBetween ¶
func (*Builder) HavingNotNull ¶
func (*Builder) HavingNull ¶
HavingNull / OrHavingNull / HavingNotNull / OrHavingNotNull: columns 支持多列(每列一条 having)。
func (*Builder) HavingRaw ¶
HavingRaw / OrHavingRaw(sql + bindings,boolean 缺省 and): 可选末位 string 参数为 boolean 关键字。
func (*Builder) IgnoreIndex ¶
IgnoreIndex 设置索引提示(ignore index)。
func (*Builder) InRandomOrder ¶
func (*Builder) IncrementEach ¶
func (b *Builder) IncrementEach(columns map[string]float64, extra map[string]interface{}) (int64, error)
IncrementEach 按列批量递增: 值编译为 raw "col + amount",extra 为附加 set 值。
func (*Builder) IncrementOrCreate ¶
func (b *Builder) IncrementOrCreate(model interface{}, attributes map[string]interface{}, column string, rest ...interface{}) error
IncrementOrCreate 创建匹配 attributes 的记录(column 取 default),已存在 则对 column 自增 step:
firstOrCreate(attributes, {column: default}) → !wasRecentlyCreated 时 increment。
rest 依次为 default(缺省 1)、step(缺省 1)、extra map[string]interface{}(附加列)。
func (*Builder) InsertGetId ¶
InsertGetId 插入并返回自增 id。
func (*Builder) InsertOrIgnore ¶
InsertOrIgnore 插入并忽略冲突行。
func (*Builder) InsertOrIgnoreReturning ¶
func (b *Builder) InsertOrIgnoreReturning(values []interface{}, returning []string, uniqueBy ...[]string) ([]map[string]any, error)
InsertOrIgnoreReturning 插入并忽略冲突行,按 returning 列返回结果行 (本库扩展 API,上游无对应实现): values 为空返回空结果不发 SQL;returning/uniqueBy 为空切片报错; 经写连接执行(对应 selectFromWriteConnection)。 编译依赖 grammar 的 CompileInsertOrIgnoreReturning 钩子——PG/SQLite 已实现, MySQL/SqlServer/MariaDB 方言未实现时调用 panic ErrUnsupported。
func (*Builder) InsertOrIgnoreUsing ¶
InsertOrIgnoreUsing insert ignore ... select。
func (*Builder) InsertUsing ¶
InsertUsing insert ... select: 只使用子查询的 cleanBindings 执行,不并入 builder 的绑定段。
func (*Builder) Join ¶
Join 添加 join 子句:Join(table, first, operator, second, type, where), operator/second 可省略,type 缺省 "inner",where 缺省 false。 first 亦可为 func(*Builder)(复杂 on 子句,JoinClause 闭包形式)。
func (*Builder) JoinLateral ¶
JoinLateral 添加 lateral join(MySQL/PG 支持,对应 joinLateral)。
func (*Builder) JoinWhere ¶
func (b *Builder) JoinWhere(table interface{}, first string, operator string, second interface{}) *Builder
JoinWhere 对应 join(..., $where=true):把第二操作数作为绑定值。
func (*Builder) LazyById ¶
func (b *Builder) LazyById(perPage uint64, column ...string) (iter.Seq2[map[string]any, error], error)
LazyById 基于 id 游标的懒加载(无大 offset 问题)。
func (*Builder) LazyByIdDesc ¶
func (b *Builder) LazyByIdDesc(perPage uint64, column ...string) (iter.Seq2[map[string]any, error], error)
LazyByIdDesc 基于 id 游标的降序懒加载。
func (*Builder) LeftJoinLateral ¶
LeftJoinLateral 添加 left lateral join。
func (*Builder) LeftJoinSub ¶
func (*Builder) LeftJoinWhere ¶
func (*Builder) LockForUpdate ¶
func (*Builder) MergeBindings ¶
MergeBindings 合并另一 builder 的绑定。
func (*Builder) MergeWheres ¶
MergeWheres 合并外部 where 数组与绑定。
func (*Builder) MorphToConstrain ¶
func (b *Builder) MorphToConstrain(name string, rel MorphTo, constraints ...func(*Builder)) *Builder
MorphToConstrain morphTo 预加载全类型通用约束(对应 MorphTo::constrain): 约束闭包应用在每个类型的 owner 查询上(先于 MorphWith 的按类型约束)。
func (*Builder) MorphToOnlyTrashed ¶
MorphToOnlyTrashed morphTo 预加载仅取已软删 owner(对应 morphTo->onlyTrashed())。
func (*Builder) MorphToWithCount ¶
func (b *Builder) MorphToWithCount(name string, rel MorphTo, perType map[string][]MorphCountSpec) *Builder
MorphToWithCount morphTo 预加载按类型的计数聚合(对应 MorphTo::morphWithCount): perType 键为类型串,值为该类型 owner 查询要加载的计数规格 (morphWithCount([Post::class => ['comments']]) 形态;Go 侧需显式 携带关系描述符,见 MorphCountSpec)。
func (*Builder) MorphToWithTrashed ¶
MorphToWithTrashed morphTo 预加载跳过目标模型软删过滤(对应 morphTo->withTrashed())。
func (*Builder) MorphToWithoutTrashed ¶
MorphToWithoutTrashed morphTo 预加载显式排除已软删 owner(对应 morphTo->withoutTrashed(); 与默认行为一致,作为显式变体提供)。
func (*Builder) MorphWith ¶
MorphWith morphTo 预加载按类型附加约束: perType 键为类型串(type 列取值),值为该类型 owner 查询的约束闭包。
func (*Builder) OnlyTrashed ¶
OnlyTrashed 只查已软删的行:deleted_at IS NOT NULL(对应 onlyTrashed 宏)。
func (*Builder) OrHavingBetween ¶
func (*Builder) OrHavingNested ¶
func (*Builder) OrHavingNotBetween ¶
func (*Builder) OrHavingNotNull ¶
func (*Builder) OrHavingNull ¶
func (*Builder) OrHavingRaw ¶
func (*Builder) OrWhereAll ¶
OrWhereAll 对应 orWhereAll。
func (*Builder) OrWhereAny ¶
OrWhereAny 对应 orWhereAny。
func (*Builder) OrWhereBetween ¶
func (*Builder) OrWhereBetweenColumns ¶
func (*Builder) OrWhereColumn ¶
func (*Builder) OrWhereDate ¶
func (*Builder) OrWhereDay ¶
func (*Builder) OrWhereDoesntHave ¶
OrWhereDoesntHave 关系不存在性约束(or 布尔)。
func (*Builder) OrWhereExists ¶
func (*Builder) OrWhereExpression ¶
OrWhereExpression 以 or 连接条件表达式。
func (*Builder) OrWhereFullText ¶
func (*Builder) OrWhereHas ¶
OrWhereHas 关系存在性约束(or 布尔)。
func (*Builder) OrWhereHasMorph ¶
func (b *Builder) OrWhereHasMorph(rel MorphMany, types []string, constraints ...func(*Builder)) *Builder
OrWhereHasMorph 多态关系存在性约束(or 布尔)。
func (*Builder) OrWhereIntegerInRaw ¶
func (*Builder) OrWhereIntegerNotInRaw ¶
func (*Builder) OrWhereJsonContains ¶
func (*Builder) OrWhereJsonContainsKey ¶
func (*Builder) OrWhereJsonDoesntContain ¶
func (*Builder) OrWhereJsonDoesntContainKey ¶
func (*Builder) OrWhereJsonDoesntHaveLength ¶
func (*Builder) OrWhereJsonDoesntOverlap ¶
OrWhereJsonDoesntOverlap 以 or 连接的 JSON 不相交( 即 whereJsonDoesntOverlap 的 or 版本)。
func (*Builder) OrWhereJsonLength ¶
func (*Builder) OrWhereJsonOverlaps ¶
func (*Builder) OrWhereKey ¶
OrWhereKey 以 or 连接主键条件(括号分组 + or)。
func (*Builder) OrWhereKeyNot ¶
OrWhereKeyNot 以 or 连接主键排除条件。
func (*Builder) OrWhereLike ¶
func (*Builder) OrWhereMonth ¶
func (*Builder) OrWhereMorphedTo ¶
OrWhereMorphedTo 匹配多态列指向特定目标的行(or 布尔)。
func (*Builder) OrWhereNested ¶
func (*Builder) OrWhereNone ¶
OrWhereNone 对应 orWhereNone。
func (*Builder) OrWhereNot ¶
func (*Builder) OrWhereNotBetween ¶
func (*Builder) OrWhereNotBetweenColumns ¶
func (*Builder) OrWhereNotExists ¶
func (*Builder) OrWhereNotIn ¶
func (*Builder) OrWhereNotLike ¶
func (*Builder) OrWhereNotNull ¶
func (*Builder) OrWhereNull ¶
func (*Builder) OrWhereNullSafeEquals ¶
OrWhereNullSafeEquals 以 or 连接的空安全等值(对应 orWhereNullSafeEquals)。
func (*Builder) OrWhereRaw ¶
func (*Builder) OrWhereRowValues ¶
func (*Builder) OrWhereTime ¶
func (*Builder) OrWhereValueBetween ¶
OrWhereValueBetween 以 or 连接(对应 orWhereValueBetween)。
func (*Builder) OrWhereValueNotBetween ¶
OrWhereValueNotBetween 以 or 连接(对应 orWhereValueNotBetween)。
func (*Builder) OrWhereYear ¶
func (*Builder) OrderBy ¶
OrderBy 排序;direction 只接受 asc/desc(大小写不敏感),非法值 panic。 column 可为 *Builder / 闭包(编译为子查询列:order by (select ...))。
func (*Builder) OrderByDesc ¶
func (*Builder) OrderByRaw ¶
func (*Builder) Paginate ¶
func (b *Builder) Paginate(dest any, page, perPage int64) (*LengthAwarePaginator, error)
Paginate 长度感知分页: 总数为 0 时不执行取数查询。
func (*Builder) Reorder ¶
Reorder 清除或重设排序: 清空 orders、unionOrders 及 order/unionOrder 段绑定;Reorder(col, dir...) 重设。
func (*Builder) ReorderDesc ¶
ReorderDesc 降序重设排序。
func (*Builder) RightJoinSub ¶
func (*Builder) RightJoinWhere ¶
func (*Builder) SetAggregate ¶
SetAggregate 设置聚合组件: groups 为空时清除 orders 与 order 段绑定。
func (*Builder) SetBindings ¶
SetBindings 覆盖某段的全部绑定。
func (*Builder) SharedLock ¶
func (*Builder) SimplePaginate ¶
func (b *Builder) SimplePaginate(dest any, page, perPage int64) (*SimplePaginator, error)
SimplePaginate 简单分页: 多取一条判断 hasMore,无 total。
func (*Builder) StraightJoin ¶
func (b *Builder) StraightJoin(table interface{}, first string, operator string, second interface{}) *Builder
StraightJoin 编译为 straight_join(仅 MySQL 支持,其它方言编译时抛错)。
func (*Builder) StraightJoinSub ¶
func (b *Builder) StraightJoinSub(q interface{}, as string, first, operator, second interface{}) *Builder
StraightJoinSub 以子查询作为 straight join 表 (仅 MySQL 支持,其它方言编译时抛错)。
func (*Builder) StraightJoinWhere ¶
func (b *Builder) StraightJoinWhere(table interface{}, first string, operator string, second interface{}) *Builder
StraightJoinWhere straight_join 且 where=true(第二操作数作为绑定值)。
func (*Builder) Touch ¶
Touch 批量刷新时间戳:把匹配行的时间戳列更新为 now。 指定列时仅更新该列(对应 touch($column));缺省列刷新 updated_at, 且仅对带时间戳列的模型建器生效(无时间戳返回 0、不发 SQL)。 直接编译 UPDATE(对应 toBase()->update):不自动追加 updated_at。
func (*Builder) UpdateFrom ¶
UpdateFrom 对应 Postgres 的 update ... from(compileUpdateFrom): 基础方言不支持(抛 ErrUnsupported)。
func (*Builder) UpdateOrCreate ¶
func (b *Builder) UpdateOrCreate(model interface{}, attributes, values map[string]interface{}) error
UpdateOrCreate 按 attributes 查找;命中则更新 values,未命中则创建 (转发 Connection.UpdateOrCreate)。
func (*Builder) UpdateOrInsert ¶
UpdateOrInsert 存在则更新,否则插入。
func (*Builder) Upsert ¶
Upsert upsert:uniqueBy 为唯一键列,update 为冲突时更新的列。 update 为空切片 → 普通 insert;update 为 nil → 全列更新(取首行的列); uniqueBy 为空抛错;values 为空返回 0。 map 行按 key 排序;query.Row 保序。
func (*Builder) When ¶
func (b *Builder) When(condition bool, callback func(*Builder), defaultCallback ...func(*Builder)) *Builder
When / Unless 条件执行:Go 侧条件为 bool。
func (*Builder) Where ¶
Where 基础 where:Where(column, value) / Where(column, operator, value, boolean...)。 column 可为字符串、grammar.Expression、map(批量 and)、func(*Builder)(括号分组)或 *Builder(子查询比较)。
func (*Builder) WhereAll ¶
func (b *Builder) WhereAll(columns []interface{}, operator string, value interface{}, boolean ...string) *Builder
WhereAll 多列 and 组内条件: where (a = ? and b = ?)。
func (*Builder) WhereAny ¶
func (b *Builder) WhereAny(columns []interface{}, operator string, value interface{}, boolean ...string) *Builder
WhereAny 多列 or 组内条件:where (a = ? or b = ?)。
func (*Builder) WhereBelongsTo ¶
WhereBelongsTo 按父模型过滤: where <singular(parentTable)_id | foreignKey> = parent 主键。
func (*Builder) WhereBetween ¶
func (b *Builder) WhereBetween(column interface{}, values []interface{}, args ...interface{}) *Builder
WhereBetween / OrWhereBetween / WhereNotBetween / OrWhereNotBetween
func (*Builder) WhereBetweenColumns ¶
WhereBetweenColumns / OrWhereBetweenColumns / WhereNotBetweenColumns / OrWhereNotBetweenColumns 两列比较的 between:values 为列名,不产生绑定。
func (*Builder) WhereColumn ¶
WhereColumn 比较两列:WhereColumn(first, second) / (first, operator, second, boolean...)。 非法操作符时回退为两参等值比较(first = second)。
func (*Builder) WhereDoesntHave ¶
WhereDoesntHave 关系不存在性约束。
func (*Builder) WhereExists ¶
WhereExists / OrWhereExists / WhereNotExists / OrWhereNotExists q 可为 func(*Builder)/func(*Builder) *Builder/ *Builder/*query.Query 闭包或子查询。
func (*Builder) WhereExpression ¶
WhereExpression 添加条件表达式: 条件原样进入 where,不追加操作符与绑定。
func (*Builder) WhereFullText ¶
func (b *Builder) WhereFullText(columns interface{}, value interface{}, options ...map[string]interface{}) *Builder
WhereFullText 全文检索:columns、value 与可选 options。
func (*Builder) WhereHas ¶
WhereHas 关系存在性约束:where exists (select * from target where keys... and constraints...) 支持 HasOne/HasMany/MorphMany/MorphOne/BelongsToMany(经 pivot 中间表)/ HasManyThrough/MorphToMany;MorphTo 无法静态判定目标类型,静默跳过(防 panic)。
func (*Builder) WhereHasMorph ¶
func (b *Builder) WhereHasMorph(rel MorphMany, types []string, constraints ...func(*Builder)) *Builder
WhereHasMorph 多态关系存在性约束: 子查询带 type 列 in (types) 过滤,types 为候选 morph key (如 []string{"posts", "videos"});constraints 应用在目标查询上。
func (*Builder) WhereIntegerInRaw ¶
WhereIntegerInRaw / OrWhereIntegerInRaw / WhereIntegerNotInRaw / OrWhereIntegerNotInRaw 整型值以 raw 形式内联进 SQL,不产生绑定。
func (*Builder) WhereIntegerNotInRaw ¶
func (*Builder) WhereJsonContains ¶
func (*Builder) WhereJsonContainsKey ¶
func (*Builder) WhereJsonDoesntContain ¶
func (*Builder) WhereJsonDoesntContainKey ¶
func (*Builder) WhereJsonDoesntHaveLength ¶
func (*Builder) WhereJsonDoesntOverlap ¶
func (*Builder) WhereJsonLength ¶
func (*Builder) WhereJsonOverlaps ¶
func (*Builder) WhereKeyNot ¶
WhereKeyNot 按主键添加排除 where: 切片编译为 whereNotIn,单值编译为 !=。
func (*Builder) WhereLike ¶
WhereLike / OrWhereLike / WhereNotLike / OrWhereNotLike 大小写敏感性由 caseSensitive 参数控制。
func (*Builder) WhereMonth ¶
func (*Builder) WhereMorphedTo ¶
WhereMorphedTo 匹配多态列指向特定目标的行: target 为已持久化模型实例(匹配 type + id)或模型零值(仅匹配 type)。
func (*Builder) WhereNested ¶
WhereNested 括号分组:WhereNested(func(nb *Builder){ nb.Where(...) })。
func (*Builder) WhereNone ¶
func (b *Builder) WhereNone(columns []interface{}, operator string, value interface{}, boolean ...string) *Builder
WhereNone 多列均不满足(or 组内条件整体取反)。
func (*Builder) WhereNotBetween ¶
func (*Builder) WhereNotBetweenColumns ¶
func (*Builder) WhereNotExists ¶
func (*Builder) WhereNotIn ¶
func (*Builder) WhereNotLike ¶
func (*Builder) WhereNotNull ¶
func (*Builder) WhereNull ¶
WhereNull / OrWhereNull / WhereNotNull / OrWhereNotNull 签名等价 whereNull(columns, boolean='and', not=false):columns 支持单列、 []string / []interface{} 多列(每列一条 where),第二参数为 boolean。
func (*Builder) WhereNullSafeEquals ¶
WhereNullSafeEquals 空安全等值比较(对应 whereNullSafeEquals): 编译为 is not distinct from(MySQL/SqlServer/SQLite 有方言实现, 基础方言走 is not distinct from)。
func (*Builder) WhereRaw ¶
WhereRaw / OrWhereRaw 签名等价 whereRaw(sql, bindings, boolean='and'):可选末位 string 参数 为 boolean 关键字(and / or / and not / or not)。
func (*Builder) WhereRowValues ¶
func (b *Builder) WhereRowValues(columns []interface{}, operator string, values []interface{}) *Builder
WhereRowValues / OrWhereRowValues: 行值比较 (a, b) = (?, ?);列数与值数必须一致。
func (*Builder) WhereValueBetween ¶
WhereValueBetween 值介于两列之间:where ? between min and max (第一参数为值, 第二参数为 [下界列, 上界列] 两元素切片)。
func (*Builder) WhereValueNotBetween ¶
WhereValueNotBetween 值不介于两列之间(对应 whereValueNotBetween)。
func (*Builder) With ¶
With 预加载关系:Get 时自动执行关联查询并填充结构体字段 (字段名 = 关系名 StudlyCase;BelongsTo/HasOne 填 *T,HasMany 填 []T)。
func (*Builder) WithAggregate ¶
func (b *Builder) WithAggregate(name string, rel Relation, function, column string, alias ...string) *Builder
WithAggregate 通用关系聚合子查询: select (select fn(col) from target where keys...) as "name_fn_col | alias"。
func (*Builder) WithConstraints ¶
func (b *Builder) WithConstraints(name string, rel Relation, constraints ...func(*Builder)) *Builder
WithConstraints 带约束闭包的预加载(对应 with(['name' => fn($q) => ...]))。
func (*Builder) WithCount ¶
WithCount 关系计数子查询:select (select count(*) ...) as "name_count"。 增强形态(对应 QueriesRelationships::withCount):
- 约束闭包:WithCount("posts", HasMany{...}, func(nb *Builder){...})
- 多关系:链式多次调用
- 嵌套点语法:WithCount("posts.comments", postsRel, commentsRel) (后续描述符逐层下钻,编译为嵌套 exists)
func (*Builder) WithExists ¶
WithExists 关系存在性聚合:select (select exists(...) ...) as "name_exists"。
func (*Builder) WithExpression ¶
WithExpression 注册公用表表达式:with "name" (columns...) as (sub) q 可为 *Builder / *query.Query / 闭包。
func (*Builder) WithLimit ¶
func (b *Builder) WithLimit(name string, rel Relation, limit int64, constraints ...func(*Builder)) *Builder
WithLimit 带限额的预加载:自动经 GroupLimit(row_number 分组)实现每组限额。
func (*Builder) WithRecursiveExpression ¶
WithRecursiveExpression 注册递归 CTE(with recursive)。
func (*Builder) WithTrashed ¶
WithTrashed 去掉软删约束(对应 SoftDeletingScope 的 withTrashed 宏)。
func (*Builder) WithoutTrashed ¶
WithoutTrashed 只查未软删的行:deleted_at IS NULL(对应 withoutTrashed 宏,默认态)。
type Collection ¶
type Collection[T any] []T
Collection 泛型集合。
func Collapse ¶
func Collapse[T any](nested Collection[[]T]) Collection[T]
Collapse 展开嵌套集合一层。 集合元素为切片类型时的包级形态(Go 方法不能按 T 约束特化)。
func (Collection[T]) Average ¶
func (c Collection[T]) Average(fields ...string) float64
Average 数值平均(空集合返回 0)。
func (Collection[T]) Chunk ¶
func (c Collection[T]) Chunk(size int) [][]T
Chunk 按 size 固定大小切块:最后一块可小于 size; size <= 0 返回 nil;空集合返回空切片。
func (Collection[T]) Contains ¶
func (c Collection[T]) Contains(pred func(T) bool) bool
Contains 是否存在满足条件的元素(谓词形态)。
func (Collection[T]) ContainsValue ¶
func (c Collection[T]) ContainsValue(want T) bool
ContainsValue 精确值形态(DeepEqual 比较)。
func (Collection[T]) ContainsWhere ¶
func (c Collection[T]) ContainsWhere(field string, args ...any) bool
ContainsWhere 字段条件形态的 contains(支持 ('field', 'value') 与 ('field', '>', value) 两种形态)。
func (Collection[T]) CountBy ¶
func (c Collection[T]) CountBy(keyFn func(T) string) map[string]int
CountBy 按回调结果分组计数(返回 map[回调值]计数; 仅有 bool 谓词形态时键为 "true"/"false")。
func (Collection[T]) CountWhere ¶
func (c Collection[T]) CountWhere(pred func(T) bool) int
CountWhere 满足谓词的元素个数(torm 保留的原"CountBy"语义)。
func (Collection[T]) CrossJoin ¶
func (c Collection[T]) CrossJoin[U any](other []U) []ZipPair[T, U]
CrossJoin 与另一切片做笛卡尔积(单数组形态): 复用 ZipPair 泛型对承载 (本集合元素, other 元素);任一侧为空返回空切片。
func (Collection[T]) Diff ¶
func (c Collection[T]) Diff(other Collection[T]) Collection[T]
Diff 差集:本集合有、other 没有的元素。
func (Collection[T]) DoesntContain ¶
func (c Collection[T]) DoesntContain(pred func(T) bool) bool
DoesntContain contains 的否定形态。
func (Collection[T]) DoesntContainWhere ¶
func (c Collection[T]) DoesntContainWhere(field string, args ...any) bool
DoesntContainWhere 字段条件的否定形态。
func (Collection[T]) Duplicates ¶
func (c Collection[T]) Duplicates() Collection[T]
Duplicates 重复元素:所有出现次数大于 1 的 值的全部出现位置,保持原顺序(与 Unique/Diff 一致按 Sprint 键判定)。
func (Collection[T]) Each ¶
func (c Collection[T]) Each(fn func(item T, index int) bool)
Each 遍历;回调返回 false 停止(break 语义)。
func (Collection[T]) Every ¶
func (c Collection[T]) Every(pred func(T) bool) bool
Every 是否全部元素满足条件:空集合返回 true。
func (Collection[T]) Except ¶
func (c Collection[T]) Except(keys ...string) []map[string]any
Except 排除指定字段后的投影。
func (Collection[T]) Filter ¶
func (c Collection[T]) Filter(pred func(T) bool) Collection[T]
Filter 过滤。
func (Collection[T]) FilterBoth ¶
func (c Collection[T]) FilterBoth(pred func(item T, index int) bool) Collection[T]
FilterBoth 带索引的过滤(回调同时接收元素与下标的双参形态)。
func (Collection[T]) Find ¶
func (c Collection[T]) Find(id any) (T, bool)
Find 按主键值查找;Go 侧按 pluck 字段比对。
func (Collection[T]) FindOrFail ¶
func (c Collection[T]) FindOrFail(id any) (T, error)
FindOrFail 按主键查找,找不到返回错误。
func (Collection[T]) First ¶
func (c Collection[T]) First(pred func(T) bool) (T, bool)
First 返回首个满足条件的元素(pred 为 nil 时取第一个)。
func (Collection[T]) FirstWhere ¶
func (c Collection[T]) FirstWhere(field string, args ...any) (T, bool)
FirstWhere 按字段条件取首个元素:
FirstWhere("name", "A") // 等于
FirstWhere("age", ">", 18) // 运算符形态(= != <> < <= > >=)
func (Collection[T]) Flatten ¶
func (c Collection[T]) Flatten(depth ...int) Collection[any]
Flatten 展开嵌套切片(depth 缺省 1 层, 元素展开为 any)。
func (Collection[T]) Forget ¶
func (c Collection[T]) Forget(indices ...int) Collection[T]
Forget 移除指定下标(可变参)的元素: 越界下标忽略;返回保留原顺序的新集合;无下标时等价 Clone。
func (Collection[T]) Fresh ¶
func (c Collection[T]) Fresh(conn *Connection) (Collection[T], error)
Fresh 按主键重查每个模型为新集合:原集合不变;行未命中的位置保留 零值占位(指针元素为 nil,保留原键位)。
func (Collection[T]) GetDictionary ¶
func (c Collection[T]) GetDictionary() map[string]T
GetDictionary 按主键的字典 map:键 = 模型主键的 Sprint 形式;非模型元素 以元素本身的 Sprint 为键。
func (Collection[T]) GetVisible ¶
func (c Collection[T]) GetVisible() ([]string, error)
GetVisible 可见列集(torm 只维护 hidden 注册表,此处返回首模型全部列减去隐藏列的可见集)。
func (Collection[T]) GroupBy ¶
func (c Collection[T]) GroupBy(keyFn func(T) string) map[string][]T
GroupBy 按回调结果分组:键为分组值,组内保持 出现顺序;Go map 无序,确定性键序用 SortKeys(grouped) 取。
func (Collection[T]) Implode ¶
func (c Collection[T]) Implode(glue string, fields ...string) string
Implode 拼接:给定时按字段提取,否则对元素 Sprint 后拼接。
func (Collection[T]) Intersect ¶
func (c Collection[T]) Intersect(other Collection[T]) Collection[T]
Intersect 交集:两边都有的元素,保留本集合顺序。
func (Collection[T]) IsNotEmpty ¶
func (c Collection[T]) IsNotEmpty() bool
func (Collection[T]) KeyBy ¶
func (c Collection[T]) KeyBy(keyFn func(T) string) map[string]T
KeyBy 以回调结果为键重建 map:重复键后出现覆盖 先出现(PHP 数组赋值语义);空集合返回空 map。
func (Collection[T]) Last ¶
func (c Collection[T]) Last(pred func(T) bool) (T, bool)
Last 返回最后一个满足条件的元素:pred 为 nil 时取 最后一个;空集合或无匹配返回零值与 false。
func (Collection[T]) MakeHidden ¶
func (c Collection[T]) MakeHidden(keys ...string) (Collection[T], error)
MakeHidden 集合内全部模型追加隐藏列。
func (Collection[T]) MakeVisible ¶
func (c Collection[T]) MakeVisible(keys ...string) (Collection[T], error)
MakeVisible 集合内全部模型解除隐藏列。
func (Collection[T]) MapWithKeys ¶
func (c Collection[T]) MapWithKeys[K comparable, V any](fn func(T) (K, V)) map[K]V
MapWithKeys 映射为 map(回调返回 (key, value))。
func (Collection[T]) Median ¶
func (c Collection[T]) Median(fields ...string) float64
Median 中位数:数值升序取中位,偶数个取中间 两数的平均;可传字段名(sum/average 同风格);无数值或空集合返回 0。
func (Collection[T]) Merge ¶
func (c Collection[T]) Merge(other Collection[T]) Collection[T]
Merge 追加合并。
func (Collection[T]) MergeHidden ¶
func (c Collection[T]) MergeHidden(keys ...string) (Collection[T], error)
MergeHidden 集合内全部模型合并隐藏列(语义与 MakeHidden 一致,追加去重)。
func (Collection[T]) Min ¶
func (c Collection[T]) Min(fields ...string) any
Min 最小值:无字段名时比较元素本身, 返回 any(空集合返回 nil)。
func (Collection[T]) Mode ¶
func (c Collection[T]) Mode() (T, bool)
Mode 众数:按 Sprint 键计数取频次最高的元素; 并列时取原顺序中最先出现者;空集合返回 (零值, false)。
func (Collection[T]) Only ¶
func (c Collection[T]) Only(keys ...string) []map[string]any
Only 取每项的指定字段投影为 map(结构体集合上按 Go 字段名/torm 列名提取)。
func (Collection[T]) Pad ¶
func (c Collection[T]) Pad(size int, def T) Collection[T]
Pad 补齐到指定长度:size 为正从尾部补 def, 为负从头部补;|size| 不大于原长度时截断。
func (Collection[T]) Partition ¶
func (c Collection[T]) Partition(pred func(T) bool) (Collection[T], Collection[T])
Partition 按谓词一分为二:(满足, 不满足)。
func (Collection[T]) Pluck ¶
func (c Collection[T]) Pluck(field string) []any
Pluck 按字段名(torm 列名或 Go 字段名)提取值集合。
func (Collection[T]) Pop ¶
func (c Collection[T]) Pop() (T, Collection[T], bool)
Pop 弹出最后一个元素:返回 (末元素, 去掉末元素的 新集合, 是否成功);空集合返回 (零值, 空集合, false)。
func (Collection[T]) Pull ¶
func (c Collection[T]) Pull(index int) (T, Collection[T], bool)
Pull 取走指定下标元素并从集合移除(键即切片 下标):返回 (元素, 移除后的新集合, 是否成功);下标越界返回 (零值, 原集合, false)。
func (Collection[T]) Push ¶
func (c Collection[T]) Push(item T) Collection[T]
Push 追加单个元素。Go 侧沿用本集合层的不可变 约定:返回追加后的新集合,原集合不变。
func (Collection[T]) Random ¶
func (c Collection[T]) Random(n int) Collection[T]
Random 随机取 n 个:抽 n 个不重复下标后按 原顺序输出(保序语义);n <= 0 返回空集合; n 大于长度时收敛为长度(Go 侧按惯例收敛)。
func (Collection[T]) Reduce ¶
func (c Collection[T]) Reduce[U any](fn func(acc U, item T) U, initial U) U
Reduce 折叠。
func (Collection[T]) Reject ¶
func (c Collection[T]) Reject(pred func(T) bool) Collection[T]
Reject 过滤的逆操作。
func (Collection[T]) SetHidden ¶
func (c Collection[T]) SetHidden(keys ...string) (Collection[T], error)
SetHidden 替换集合内全部模型的隐藏列集:先全量 MakeVisible 清空再追加新集。
func (Collection[T]) Shuffle ¶
func (c Collection[T]) Shuffle() Collection[T]
Shuffle 随机打乱:math/rand 全局 rand.Shuffle, 返回打乱后的新集合,原集合不变。
func (Collection[T]) SliceRange ¶
func (c Collection[T]) SliceRange(offset, length int) Collection[T]
SliceRange 子切片(slice($offset, $length) 语义):offset 起始, length 为个数,负值 length 表示取到末尾(等价 null 语义)。 与 Slice()(返回底层切片)并存,以 Range 后缀区分。
func (Collection[T]) Some ¶
func (c Collection[T]) Some(pred func(T) bool) bool
Some 是否存在满足条件的元素(contains 的别名)。
func (Collection[T]) SortBy ¶
func (c Collection[T]) SortBy(less func(a, b T) bool) Collection[T]
SortBy 比较函数排序(稳定;Go 侧传 less 闭包)。
func (Collection[T]) SortByDesc ¶
func (c Collection[T]) SortByDesc(less func(a, b T) bool) Collection[T]
SortByDesc 降序排序:对齐既有 SortBy 的 less 比较器约定,稳定排序;返回新集合。
func (Collection[T]) Split ¶
func (c Collection[T]) Split(n int) [][]T
Split 按组数均分:组大小取 ceil(len/n)(向上取整),末组可更短;n <= 0 返回 nil;空集合返回空切片。
func (Collection[T]) Sum ¶
func (c Collection[T]) Sum(fields ...string) float64
Sum 数值求和:无字段名时直接对元素求和,有字段名时按字段提取 (非数值跳过)。
func (Collection[T]) TakeUntil ¶
func (c Collection[T]) TakeUntil(pred func(T) bool) Collection[T]
TakeUntil 取到首个满足条件的元素为止(不含该元素,任务清单中的 Until 方法):无元素满足时返回全量;空集合返回空。
func (Collection[T]) Tap ¶
func (c Collection[T]) Tap(fn func(Collection[T])) Collection[T]
Tap 副作用钩子:调用 fn(c) 后原样返回集合。
func (Collection[T]) ToQuery ¶
func (c Collection[T]) ToQuery(conn *Connection) (*Builder, error)
ToQuery 首个模型的新查询构造器(以集合首模型 的 newQuery 为底座)。集合为空、conn 为 nil 或元素不是模型时报错 (Go 模型不内嵌连接,需显式传入连接上下文)。
func (Collection[T]) Union ¶
func (c Collection[T]) Union(other Collection[T]) Collection[T]
Union 合并去重(保留首次出现;Go 侧按 Sprint 键判定重复)。
func (Collection[T]) UniqueBy ¶
func (c Collection[T]) UniqueBy(key func(T) any) Collection[T]
UniqueBy 按键函数去重。
func (Collection[T]) Unless ¶
func (c Collection[T]) Unless(cond bool, fn func(Collection[T]) Collection[T]) Collection[T]
Unless 条件为假时应用变换。
func (Collection[T]) When ¶
func (c Collection[T]) When(cond bool, fn func(Collection[T]) Collection[T]) Collection[T]
When 条件为真时应用变换。
func (Collection[T]) Zip ¶
func (c Collection[T]) Zip[U any](other []U) []ZipPair[T, U]
Zip 与另一切片按位配对,长度取较小者(Go 侧不产生 null 占位,多余元素丢弃)。
type Config ¶
type Config struct {
// Database 数据库名(对应 config['database'],内省与
// CreateDatabase 使用)
Database string
Driver string
Prefix string
Dsn string
ReadDsn string // 兼容:单个只读 DSN(读写分离,select 类查询路由到此)
// ReadDsns 只读 DSN 池:建连时随机选一(对应配置 read 数组 + Arr::random)。
ReadDsns []string
// Sticky sticky 模式:本连接发生写操作后,后续读强制走主连接
// (对应配置 sticky,配合 recordsModified 跟踪)。
Sticky bool
// StickyWindowSec sticky 时间窗(秒):>0 时写后该窗口内读走主库、
// 窗口外恢复读写分离(默认 0 = 进程生命周期内永久粘主,1.x 语义;
// 其他实现为请求级语义,Go 无请求上下文时建议配置窗口)。
StickyWindowSec int
// MySQL 连接参数(MySqlConnector 自动附加到 DSN,已有参数不覆盖)
Charset string // NAMES charset
Collation string // COLLATE collation
SqlMode string // SESSION sql_mode
Timezone string // time_zone
// Modes sql_mode 数组(对应 config['modes'],join 后优先于 SqlMode 单串)
Modes []string
// Postgres / SQLServer
IsolationLevel string // 会话事务隔离级别(建连后以 SET 语句生效)
SslMode string // Postgres sslmode
SearchPath string // Postgres search_path
SslCert string // Postgres sslcert DSN 参数
SslKey string // Postgres sslkey DSN 参数
SslRootCert string // Postgres sslrootcert DSN 参数
// SynchronousCommit Postgres synchronous_commit(建连后 set synchronous_commit to)
SynchronousCommit string
// ClientEncoding / ApplicationName Postgres DSN 参数
ClientEncoding string
ApplicationName string
// SQLite pragmas
ForeignKeys *bool // PRAGMA foreign_keys(nil = 默认开启,与 sqlite 默认 foreign_keys=true 一致)
BusyTimeout int // PRAGMA busy_timeout(毫秒,0 表示不设置)
JournalMode string // PRAGMA journal_mode
Synchronous string // PRAGMA synchronous
// Pragmas 自定义 pragma 集合(对应 config['pragmas'],经 DSN _pragma 参数生效,
// 连接池下每个物理连接均生效)
Pragmas map[string]string
// MySQL 方言开关(GetQueryGrammar 注入;此前仅 schema 侧可达,查询侧死代码)
ServerVersion string // 如 "8.0.36" / "10.5.2-MariaDB"(MySQL 5.7 分支、JSON 能力判定)
IsMariaDB bool // driver="mysql" 但实际为 MariaDB 时标记(影响 JSON/upsert 编译)
UseUpsertAlias *bool // MySQL 8.0.19+ 关闭 as 别名 upsert(nil = 按版本推断)
UseLegacyGroupLimit bool // SQLite < 3.25 的 groupLimit 降级分支
// 连接池调优(对应 database/sql 的 Set* API;0 值 = 不设置,保留驱动默认)
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetimeSec int // 连接最长存活时间(秒,0 = 不设置)
ConnMaxIdleTimeSec int // 连接最长空闲时间(秒,0 = 不设置)
// ParseTime MySQL DSN 是否自动附加 parseTime=true(nil/true = 附加,
// time.Time 字段扫描必需;显式 false 关闭注入)
ParseTime *bool
}
Config 连接配置(对应配置文件中的 database.connections 节点)。
type Connection ¶
func (*Connection) AddObserver ¶
func (c *Connection) AddObserver(model any, o *Observer)
AddObserver 追加注册观察者(observe 可叠加语义; 按注册顺序执行,任一返回 error 中断)。
func (*Connection) AfterCommit ¶
func (c *Connection) AfterCommit(fn func())
AfterCommit 注册事务提交后的回调;注册时无活动事务则立即执行,嵌套事务中 注册的回调在其所在层级提交时上浮,最外层提交后统一执行;所在事务回滚时被 丢弃(对齐 DatabaseTransactionsManager::addCallback)。
func (*Connection) AfterRollBack ¶
func (c *Connection) AfterRollBack(fn func())
AfterRollBack 注册回滚回调:所在事务(或其内层)发生回滚时执行。无活动 事务时回调被静默丢弃(对齐 DatabaseTransactionsManager::addCallbackForRollback)。
func (*Connection) Attach ¶
func (c *Connection) Attach(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) error
Attach 建立 pivot 关联(对应 attach;BelongsToMany / MorphToMany 均可): 单条多值 INSERT(每 100 行一批,规避 SQLite 变量上限与 SQLServer 1000 行 限制);pivotAttrs 为附加列值,WithPivotValue 固定值打底、显式 attrs 覆盖; PivotTimestamps 时自动带 created_at/updated_at。parent 可为模型或其主键值。
func (*Connection) AttachOrFail ¶
func (c *Connection) AttachOrFail(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any)
AttachOrFail 建立 pivot 关联,失败 panic *FailError{Op:"attach"}。
func (*Connection) BeforeExecuting ¶
func (c *Connection) BeforeExecuting(fn func(query string, bindings []any))
BeforeExecuting 注册每条语句执行前的回调。
func (*Connection) BeforeStartingTransaction ¶
func (c *Connection) BeforeStartingTransaction(fn func())
BeforeStartingTransaction 注册事务开始前的回调。
func (*Connection) BeginTransaction ¶
func (c *Connection) BeginTransaction() error
BeginTransaction 开启事务;嵌套时创建 savepoint(嵌套事务管理)。 level 0 的 BEGIN 遇断连错误重连后重试一次 (handleBeginTransactionException)。
func (*Connection) Commit ¶
func (c *Connection) Commit() error
Commit 提交当前事务层;仅最外层提交到数据库。afterCommit 回调在释放事务 锁之后执行:回调内允许再次调用 TransactionLevel/AfterCommit/Commit 而不会 自死锁(commit() 在锁外通知 manager)。
func (*Connection) Create ¶
func (c *Connection) Create(model interface{}) error
Create Save a new model to the database(保存新模型,事件顺序: saving → creating → 时间戳 → insert → created → saved)。
func (*Connection) CreateManyQuietly ¶
func (c *Connection) CreateManyQuietly(model any, rows []map[string]any) error
CreateManyQuietly 以 model 为原型批量静默创建(每行一个新实例)。
func (*Connection) CreateOrFirst ¶
func (c *Connection) CreateOrFirst(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error
CreateOrFirst 先尝试创建,唯一约束冲突时回退按 attributes 查询 (createOrFirst 的并发安全语义)。
func (*Connection) CreateOrRestore ¶
func (c *Connection) CreateOrRestore(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error
CreateOrRestore 软删模型版 createOrFirst:先创建,唯一约束冲突时 withTrashed 查回已存在行并恢复(createOrRestore 语义)。
func (*Connection) CreateQuietly ¶
func (c *Connection) CreateQuietly(model any) error
CreateQuietly 创建模型但不触发任何事件。
func (*Connection) CursorQuery ¶
func (c *Connection) CursorQuery(query string, bindings []interface{}, forceWrite bool) (iter.Seq2[map[string]any, error], error)
CursorQuery 打开流式查询;返回的迭代器逐行产出 map,迭代结束或提前终止时自动关闭。 扫描/驱动错误通过 iter.Seq2 的 error 通道传出。
func (*Connection) Decrement ¶
func (c *Connection) Decrement(model any, column string, amount ...any) error
Decrement 自减一列;amount 缺省 1,可传 map[string]any 作为 extra 附加列。
func (*Connection) DecrementEach ¶
func (c *Connection) DecrementEach(model any, columns map[string]int64, extra ...map[string]any) error
DecrementEach 一条 UPDATE 内自减多列。
func (*Connection) Delete ¶
func (c *Connection) Delete(query string, args ...interface{}) (int64, error)
Delete Run a delete statement against the database.
func (*Connection) DeleteModel ¶
func (c *Connection) DeleteModel(model interface{}) error
DeleteModel 删除模型:软删除模型置 deleted_at(同步 updated_at), 否则硬删除(命名避开 Connection.Delete 的原生 SQL 方法;模型删除 与软删:deleting → UPDATE → trashed → deleted)。
func (*Connection) DeleteOrFail ¶
func (c *Connection) DeleteOrFail(model any) error
DeleteOrFail 删除模型,失败 panic *FailError。
func (*Connection) DeleteQuietly ¶
func (c *Connection) DeleteQuietly(model any) error
DeleteQuietly 删除模型但不触发任何事件。
func (*Connection) Destroy ¶
func (c *Connection) Destroy(model interface{}) error
Destroy 按主键硬删除模型行(delete 的硬删分支); 主键为空时返回错误,绝不执行整表 DELETE。
func (*Connection) DestroyByIDs ¶
func (c *Connection) DestroyByIDs(model interface{}, ids ...interface{}) (int, error)
DestroyByIDs 按主键批量删除(静态 destroy 语义:逐个加载模型并 走完整删除生命周期,软删模型执行软删)。返回成功删除的个数。
func (*Connection) Detach ¶
func (c *Connection) Detach(parent any, rel PivotRelation, ids ...any) (int64, error)
Detach 解除 pivot 关联(对应 detach):ids 为空时解除全部,返回受影响行数。
func (*Connection) DetachOrFail ¶
func (c *Connection) DetachOrFail(parent any, rel PivotRelation, ids ...any) int64
DetachOrFail 解除 pivot 关联,失败 panic *FailError{Op:"detach"},返回受影响行数。
func (*Connection) DisableQueryLog ¶
func (c *Connection) DisableQueryLog()
DisableQueryLog 关闭内存查询日志(不清空已记录内容)。
func (*Connection) Escape ¶
func (c *Connection) Escape(value any, binary ...bool) (string, error)
Escape 为安全 SQL 内嵌转义值(对应 Connection::escape):null → 'null'、 bool 按 escapeBool、整数/浮点原样、字符串单引号双写(含 NUL 字节或非法 UTF-8 时报错);binary=true 时按方言转义二进制。
func (*Connection) FirstOrCreate ¶
func (c *Connection) FirstOrCreate(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error
FirstOrCreate 按 attributes 查找;未命中则合并 attributes+values 创建模型 (firstOrCreate(attributes, values) 语义:赋值走 fill 守卫语义)。
func (*Connection) FirstOrNew ¶
func (c *Connection) FirstOrNew(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error
FirstOrNew 按 attributes 查找;未命中仅以 attributes+values 构造不落库 (firstOrNew(attributes, values) 语义)。
func (*Connection) ForceDelete ¶
func (c *Connection) ForceDelete(model interface{}) error
ForceDelete 绕过软删除硬删除;主键为空时返回错误,绝不执行整表 DELETE。
func (*Connection) ForceDeleteQuietly ¶
func (c *Connection) ForceDeleteQuietly(model any) error
ForceDeleteQuietly 硬删模型但不触发任何事件。
func (*Connection) ForgetRecordModificationState ¶
func (c *Connection) ForgetRecordModificationState()
ForgetRecordModificationState 重置写标记(对应 forgetRecordModificationState)。
func (*Connection) Fresh ¶
func (c *Connection) Fresh(model any) (any, error)
Fresh 按主键重查一个全新实例(fresh 语义):原模型保持不变; 模型未持久化或行未命中返回 nil。
func (*Connection) GetConfig ¶
func (c *Connection) GetConfig() Config
GetConfig 返回连接配置(对应 Connection::getConfig)。
func (*Connection) GetDatabaseName ¶
func (c *Connection) GetDatabaseName() string
GetDatabaseName 返回数据库名(对应 Connection::getDatabaseName)。
func (*Connection) GetQueryGrammar ¶
func (c *Connection) GetQueryGrammar() grammar.Grammar
GetQueryGrammar 按 driver 构造方言 grammar,并接线上表前缀与 Config 方言 开关(ServerVersion/IsMariaDB/UseUpsertAlias/UseLegacyGroupLimit——此前这些 setter 只有 schema 侧可达,查询路径上是死代码)。 按 driver 做方言分发:PG/SQLite/ SqlServer/MariaDb 连接必须路由到各自的语法编译器,否则运行时全部按 MySQL 语法编译。
func (*Connection) GetQueryLog ¶
func (c *Connection) GetQueryLog() []QueryExecuted
GetQueryLog 返回已记录的查询日志快照。
func (*Connection) GetRawQueryLog ¶
func (c *Connection) GetRawQueryLog() []RawQueryLog
GetRawQueryLog 返回绑定插值后的查询日志(对应 Connection::getRawQueryLog: substituteBindingsIntoRawSql 套用在现有 QueryLog 上)。
func (*Connection) GetSchemaGrammar ¶
func (c *Connection) GetSchemaGrammar() grammar.SchemaGrammar
GetSchemaGrammar 按驱动返回 DDL 编译器。 对应各驱动的 getConnection → getSchemaGrammar 方言分发。
func (*Connection) HasModifiedRecords ¶
func (c *Connection) HasModifiedRecords() bool
HasModifiedRecords 报告自上次重置以来是否发生过写操作。
func (*Connection) Increment ¶
func (c *Connection) Increment(model any, column string, amount ...any) error
Increment 自增一列;amount 缺省 1,可传 map[string]any 作为 extra 附加列。
func (*Connection) IncrementEach ¶
func (c *Connection) IncrementEach(model any, columns map[string]int64, extra ...map[string]any) error
IncrementEach 一条 UPDATE 内自增多列; extra 为附加列。金额为负值时转为自减。
func (*Connection) Insert ¶
func (c *Connection) Insert(query string, args ...interface{}) (int64, int64, error)
Insert Run an insert statement against the database.
func (*Connection) InsertGetId ¶
func (c *Connection) InsertGetId(query string, args ...interface{}) (int64, error)
InsertGetId 执行 insert 并返回自增 id。 PG/SQLServer 的 grammar 编译同款 insert ... returning/output 语句, 驱动不支持 LastInsertId(lib/pq、mssqldb 返回 0 或报错)——改为消费返回行, 从 returning/output 结果集中取自增 id。
func (*Connection) IsMaria ¶
func (c *Connection) IsMaria() bool
IsMaria 报告服务器是否为 MariaDB:仅 mysql/mariadb 驱动按版本串判断 (含 "MariaDB"),其余驱动恒为 false。
func (*Connection) Listen ¶
func (c *Connection) Listen(fn func(QueryExecuted))
Listen 注册查询事件监听器(对应 Connection::listen,支持多监听器)。
func (*Connection) Load ¶
func (c *Connection) Load(model any, name string, rel Relation, constraints ...func(*Builder)) error
Load 显式触发关系加载并缓存到模型: 结果经 SetLoadedRelation 缓存;模型存在同名关系字段(StudlyCase)时同步回填。
func (*Connection) LoadAggregate ¶
func (c *Connection) LoadAggregate(model any, name string, rel Relation, function, column string, rest ...any) error
LoadAggregate 通用关系聚合加载: function/column 组合如 ("count","*") / ("sum","votes");rest 支持 约束闭包、嵌套 Relation 与 string 别名(与 Builder.WithAggregate 一致)。
func (*Connection) LoadAvg ¶
func (c *Connection) LoadAvg(model any, name string, rel Relation, column string, rest ...any) error
LoadAvg 加载关系列平均(对应 loadAvg)。
func (*Connection) LoadExists ¶
LoadExists 加载关系存在性到模型 {relation}_exists 属性(对应 loadExists)。
func (*Connection) LoadMany ¶
func (c *Connection) LoadMany(model any, rels map[string]Relation) error
LoadMany 一次加载多个关系。
func (*Connection) LoadMax ¶
func (c *Connection) LoadMax(model any, name string, rel Relation, column string, rest ...any) error
LoadMax 加载关系列最大值到模型 {relation}_max_{column} 属性(对应 loadMax)。
func (*Connection) LoadMin ¶
func (c *Connection) LoadMin(model any, name string, rel Relation, column string, rest ...any) error
LoadMin 加载关系列最小值(对应 loadMin)。
func (*Connection) LoadMissing ¶
func (c *Connection) LoadMissing(model any, name string, rel Relation, constraints ...func(*Builder)) error
LoadMissing 惰性加载已加载则跳过的关系(relationLoaded 时直接返回, 不发关联查询)。
func (*Connection) LoadMorph ¶
func (c *Connection) LoadMorph(model any, name string, rel Relation) error
LoadMorph 加载单模型的多态关系(实例级入口): MorphMany/MorphOne 经 builder 内部 loadMorph 查回子模型并填充同名关系 字段,同时写入 LoadedRelation 缓存;其它关系类型走 Load 通道。
func (*Connection) LoadMorphCount ¶
func (c *Connection) LoadMorphCount(model any, name string, rel Relation) error
LoadMorphCount 加载多态关系计数到模型 {relation}_count 属性 (loadMorphCount 的实例级入口)。
func (*Connection) LoadSum ¶
func (c *Connection) LoadSum(model any, name string, rel Relation, column string, rest ...any) error
LoadSum 加载关系列求和(对应 loadSum)。
func (*Connection) Model ¶
func (c *Connection) Model(model interface{}) *Builder
Model Begin a fluent query against a database Model. 含软删除全局 scope(deleted_at IS NULL)。
func (*Connection) Observe ¶
func (c *Connection) Observe(model any, o *Observer)
Observe 为模型类型注册观察者(覆盖式:替换该类型当前的全部观察者, 与 1.x 行为一致)。需要叠加多个观察者时使用 AddObserver。
func (*Connection) OnQuery ¶
func (c *Connection) OnQuery(fn func(QueryExecuted))
OnQuery 注册查询事件回调(兼容接口:单回调,重复设置时覆盖)。
func (*Connection) Pretend ¶
func (c *Connection) Pretend(fn func(*Connection)) []QueryExecuted
Pretend 以 dry-run 方式执行回调(对应 Connection::pretend):查询被记录 但不真正发往数据库;返回期间记录的查询日志。
func (*Connection) Push ¶
func (c *Connection) Push(model any) error
Push 保存模型及其全部已加载关系(递归): 关系取 LoadedRelation 缓存(Load/LoadMany 显式加载的结果), 逐个递归 Push;已访问模型跳过(防环)。
func (*Connection) PushQuietly ¶
func (c *Connection) PushQuietly(model any) error
PushQuietly 保存模型与已加载关系但不触发任何事件。
func (*Connection) Query ¶
func (c *Connection) Query() *Builder
Query Get a new query builder instance.
func (*Connection) Raw ¶
func (c *Connection) Raw(value string) grammar.Expression
Raw 返回原始 SQL 表达式(对应 Connection::raw)。
func (*Connection) RecordsHaveBeenModified ¶
func (c *Connection) RecordsHaveBeenModified(value bool)
RecordsHaveBeenModified 显式设置写标记。
func (*Connection) Refresh ¶
func (c *Connection) Refresh(model any) error
Refresh 重查并刷新原模型属性(refresh 语义):按主键重查 (不带软删 scope,已软删模型同样可刷新),把查得属性整体覆盖进原模型 并同步 original 快照;行已消失返回 *ErrNotFound(firstOrFail 语义)。
func (*Connection) RelationCreate ¶
func (c *Connection) RelationCreate(parent any, rel Relation, attributes map[string]any) (any, error)
---- 关系级写方法(对应 HasOneOrMany.php:228-485、MorphOneOrMany.php:330-370)---- RelationCreate 创建关联模型并自动填外键(morph 关系同时填类型列), 走完整 Create 生命周期;rel 支持 HasOne/HasMany/MorphOne/MorphMany。
func (*Connection) RelationFind ¶
RelationFind 关系内按目标模型主键查找(对应 BelongsToMany::find / HasOneOrMany::find):按主键在关系结果内匹配,无命中返回 (nil, nil)。 统一在内存中按主键过滤——对 pivot/中间表 join 形态(BelongsToMany 等 GetResults 不做约束下推的关系)与普通关系行为一致。
func (*Connection) RelationFirst ¶
func (c *Connection) RelationFirst(parent any, rel Relation, constraints ...func(*Builder)) (any, error)
RelationFirst 关系内取首条(对应 first):constraints 附加在关系查询上 (键形态关系做 SQL 下推;BelongsToMany/MorphToMany/through 形态的 GetResults 不下推约束,为 best-effort);无命中返回 (nil, nil)。
func (*Connection) RelationFirstOr ¶
func (c *Connection) RelationFirstOr(parent any, rel Relation, fallback func() (any, error), constraints ...func(*Builder)) (any, error)
RelationFirstOr 关系内取首条,无命中走 fallback(对应 firstOr($callback))。
func (*Connection) RelationFirstOrCreate ¶
func (c *Connection) RelationFirstOrCreate(parent any, rel Relation, attributes map[string]any, values ...map[string]any) (any, error)
RelationFirstOrCreate 按外键 + attributes 查找或创建关联模型。
func (*Connection) RelationFirstOrFail ¶
func (c *Connection) RelationFirstOrFail(parent any, rel Relation, constraints ...func(*Builder)) any
RelationFirstOrFail 关系内取首条;无命中或查询出错 panic *FailError (对应 firstOrFail 抛 ModelNotFoundException,ErrNotFound 可经 Unwrap 取回)。
func (*Connection) RelationSave ¶
func (c *Connection) RelationSave(parent any, rel Relation, related any) error
RelationSave 保存关联模型:先填外键(+morph type)再 Save (无主键 → insert,有主键 → update 脏列)。
func (*Connection) RelationSole ¶
func (c *Connection) RelationSole(parent any, rel Relation, constraints ...func(*Builder)) (any, error)
RelationSole 关系内取唯一一条(对应 sole):0 条 → ErrNotFound, 多条 → ErrMultiple。
func (*Connection) RelationUpdateOrCreate ¶
func (c *Connection) RelationUpdateOrCreate(parent any, rel Relation, attributes, values map[string]any) (any, error)
RelationUpdateOrCreate 按外键 + attributes 查找并更新,或创建新关联模型。
func (*Connection) Replicate ¶
func (c *Connection) Replicate(dst, src any) error
Replicate 把已持久化模型复制为未持久化新实例写入 dst: 主键与时间戳清零、状态清除(对齐 replicate 语义:excluding $primaryKey / createdAt / updatedAt);replicating 观察者在副本上触发 (可修改副本、返回 error 取消)。
func (*Connection) ResetTotalQueryDuration ¶
func (c *Connection) ResetTotalQueryDuration()
ResetTotalQueryDuration 清零累计查询耗时。
func (*Connection) Restore ¶
func (c *Connection) Restore(model interface{}) error
Restore 恢复软删除的模型(事件顺序: Restoring → deleted_at 置空 + updated_at 刷新(经完整 save 生命周期)→ Restored)。
func (*Connection) RestoreOrCreate ¶
func (c *Connection) RestoreOrCreate(model interface{}, attributes map[string]interface{}, values ...map[string]interface{}) error
RestoreOrCreate 软删模型版 firstOrCreate:withTrashed 查找,命中且已软删 则恢复(restoreOrCreate 语义)。
func (*Connection) RestoreQuietly ¶
func (c *Connection) RestoreQuietly(model any) error
RestoreQuietly 恢复软删模型但不触发任何事件。
func (*Connection) RollBack ¶
func (c *Connection) RollBack() error
RollBack 回滚到上一层事务;toLevel<0 或越界时为 no-op。
func (*Connection) RollBackToLevel ¶
func (c *Connection) RollBackToLevel(toLevel int) error
RollBackToLevel 回滚到指定事务层。
func (*Connection) Save ¶
func (c *Connection) Save(model interface{}) error
Save Save the model to the database(保存/更新): saving → 干净模型 short-circuit(仅 saved,不发 SQL 不触发 updating/updated); 存在记录(exists)→ updating → 时间戳 → 脏列 UPDATE → updated;否则 → creating → 时间戳 → INSERT(以 exists 而非主键 是否为空决定插入/更新)。
func (*Connection) SaveOrFail ¶
func (c *Connection) SaveOrFail(model any) error
SaveOrFail 事务内保存模型,失败 panic *FailError。
func (*Connection) SaveOrIgnore ¶
func (c *Connection) SaveOrIgnore(model any) (bool, error)
SaveOrIgnore 未持久化模型以 insert or ignore 写入:唯一约束冲突时静默 跳过并返回 (false, nil);已持久化(exists)模型返回错误。 成功时固时间戳、回填自增主键、置 exists/wasRecentlyCreated 并触发 creating/created/saved 事件(对齐 performInsertOrIgnore 生命周期)。 差异说明:uniqueBy 形参需经 insertOrIgnoreReturning 下推到方言 编译,Go 侧编译钩子待接线(见待接线清单),故不提供该参数。
func (*Connection) SaveQuietly ¶
func (c *Connection) SaveQuietly(model any) error
SaveQuietly 保存模型但不触发任何事件。
func (*Connection) Scalar ¶
func (c *Connection) Scalar(query string, bindings []interface{}) (any, error)
Scalar Run a select statement and return the first column of the first row (对应 Connection::scalar);多列时返回 ErrMultipleColumnsSelected。
func (*Connection) Scan ¶
func (c *Connection) Scan(query string, bindings []interface{}, dest ...interface{}) error
Scan Run a query and scan columns into given destinations.
func (*Connection) Select ¶
func (c *Connection) Select(query string, bindings []interface{}, dest interface{}) error
Select Run a select statement against the database.
func (*Connection) SelectFromWrite ¶
func (c *Connection) SelectFromWrite(query string, bindings []interface{}, dest interface{}) error
SelectFromWrite 强制走写连接的 select(忽略读连接路由)。
func (*Connection) SelectMaps ¶
func (c *Connection) SelectMaps(query string, bindings []interface{}) ([]map[string]any, error)
SelectMaps 执行查询并把行结果输出为 map 切片(explain/内省用)。
func (*Connection) SelectOne ¶
func (c *Connection) SelectOne(query string, bindings []interface{}, dest interface{}) error
SelectOne Run a select statement and return a single result(只取第一行, 等价于 select 后 array_shift 的语义)。
func (*Connection) SelectResultSets ¶
func (c *Connection) SelectResultSets(query string, bindings []interface{}) ([][]map[string]any, error)
SelectResultSets 执行查询并返回全部结果集(对应 selectResultSets)。 Go database/sql 单条语句只产出单个结果集,故返回包含一个结果集的切片。
func (*Connection) ServerVersion ¶
func (c *Connection) ServerVersion() (string, error)
ServerVersion 返回数据库服务器版本(对应 PDO::ATTR_SERVER_VERSION)。 惰性求值并按驱动选择版本查询:mysql/mariadb/postgres 走 select version(), sqlite 走 select sqlite_version(),sqlserver 走 select serverproperty('ProductVersion');仅首次真正查询,结果加锁缓存。
func (*Connection) SetConnectionName ¶
func (c *Connection) SetConnectionName(name string)
SetConnectionName 设置连接名(错误消息与事件将携带该名称)。
func (*Connection) SetDatabaseName ¶
func (c *Connection) SetDatabaseName(name string)
SetDatabaseName 设置数据库名(对应 Connection::setDatabaseName)。
func (*Connection) SetEventDispatcher ¶
func (c *Connection) SetEventDispatcher(d events.Dispatcher)
SetEventDispatcher 挂载事件分发器;生命周期点将同步分发事件对象。 ConnectionEstablished 由 Open/Manager 在建连时经已挂载的分发器分发 (Manager.SetEventDispatcher 提供管理器级挂载点)。
func (*Connection) SetReconnector ¶
func (c *Connection) SetReconnector(fn func(*Connection) error)
SetReconnector 设置断连重连回调(对应 Connection::setReconnector): reconnect() 优先调用该回调。
func (*Connection) SetRecordModificationState ¶
func (c *Connection) SetRecordModificationState(value bool)
SetRecordModificationState 无条件设置写标记。
func (*Connection) Statement ¶
func (c *Connection) Statement(query string, args ...interface{}) error
Statement Execute an SQL statement and return the boolean result.
func (*Connection) Sync ¶
func (c *Connection) Sync(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) (*SyncResult, error)
Sync 全量同步 pivot(对应 sync):附加缺失、解除多余、更新现存(带 pivotAttrs 时),返回 attached/detached/updated。
func (*Connection) SyncOrFail ¶
func (c *Connection) SyncOrFail(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) *SyncResult
SyncOrFail 全量同步 pivot,失败 panic *FailError{Op:"sync"}。
func (*Connection) SyncWithPivotValues ¶
func (c *Connection) SyncWithPivotValues(parent any, rel PivotRelation, ids []any, values map[string]any, detaching ...bool) (*SyncResult, error)
SyncWithPivotValues 以给定 pivot 值同步 ids(对应 syncWithPivotValues): 缺失的附加(带 values)、现存的更新 values;detaching=false 时 syncWithoutDetaching 语义(不解除其它关联)。ids 可为模型或裸键。
func (*Connection) SyncWithoutDetaching ¶
func (c *Connection) SyncWithoutDetaching(parent any, rel PivotRelation, ids []any, pivotAttrs ...map[string]any) (*SyncResult, error)
SyncWithoutDetaching 同步但不解除缺失项(对应 syncWithoutDetaching)。
func (*Connection) Table ¶
func (c *Connection) Table(table string) *Builder
Table Begin a fluent query against a database table.
func (*Connection) ThreadCount ¶
func (c *Connection) ThreadCount() (int, error)
ThreadCount 返回数据库打开的连接/线程数(对应 Connection::threadCount): 驱动不支持时返回 (-1, nil)。
func (*Connection) Toggle ¶
func (c *Connection) Toggle(parent any, rel PivotRelation, ids []any) (*SyncResult, error)
Toggle 切换 pivot 关联(对应 toggle):已关联的解除、未关联的附加。
func (*Connection) ToggleOrFail ¶
func (c *Connection) ToggleOrFail(parent any, rel PivotRelation, ids []any) *SyncResult
ToggleOrFail 切换 pivot 关联,失败 panic *FailError{Op:"toggle"}。
func (*Connection) TotalQueryDuration ¶
func (c *Connection) TotalQueryDuration() float64
TotalQueryDuration 返回累计查询耗时(毫秒)。
func (*Connection) Touch ¶
func (c *Connection) Touch(model any) error
Touch 以 now 刷新 updated_at 后走完整 save 生命周期。
func (*Connection) TouchOwners ¶
func (c *Connection) TouchOwners(model any) error
TouchOwners 触碰模型声明关系(torm:"touches=name" tag)指向的父模型时间戳 (对应 HasRelationships::touchOwners,最小实现)。关系已惰性加载 (LoadedRelation)时逐个 touch 已加载的父模型实例并递归其 touches; 否则按 belongsTo 键约定反查:父表 = pluralize(关系名),外键 = 关系名_id, 执行 update <parent> set updated_at = now where id = <fk 值>。 Save/Delete/软删生命周期自动触发(model.go 的 Save/DeleteModel/Restore 在成功写库后调用 TouchOwners)。
func (*Connection) TouchQuietly ¶
func (c *Connection) TouchQuietly(model any) error
TouchQuietly 刷新 updated_at 但不触发任何事件。
func (*Connection) Transaction ¶
func (c *Connection) Transaction(fn func(*Connection) error, attempts ...int) error
Transaction 在事务中执行回调。最外层遇到死锁/锁等待时回滚并重试(最多 attempts 次,默认 1);嵌套调用降级为 savepoint,任何错误都回滚到进入前的 层级并把错误交还外层处理——嵌套层级不自行重试 (handleTransactionException:仅最外层事务参与重试)。
func (*Connection) TransactionLevel ¶
func (c *Connection) TransactionLevel() int
TransactionLevel 返回当前事务层数。
func (*Connection) Unprepared ¶
func (c *Connection) Unprepared(query string) (bool, error)
Unprepared 直发一条未预处理 SQL(对应 Connection::unprepared):绕过 run 包装(不重试、不计时不写查询日志),成功后标记已发生写操作; pretending 时返回 (true, nil)。
func (*Connection) UnsetEventDispatcher ¶
func (c *Connection) UnsetEventDispatcher()
UnsetEventDispatcher 卸载事件分发器(对应 Connection::unsetEventDispatcher)。
func (*Connection) Update ¶
func (c *Connection) Update(query string, args ...interface{}) (int64, error)
Update Run an update statement against the database.
func (*Connection) UpdateExistingPivot ¶
func (c *Connection) UpdateExistingPivot(parent any, rel PivotRelation, id any, attrs map[string]any) (int64, error)
UpdateExistingPivot 更新现存 pivot 行(对应 updateExistingPivot),返回受影响行数。
func (*Connection) UpdateExistingPivotOrFail ¶
func (c *Connection) UpdateExistingPivotOrFail(parent any, rel PivotRelation, id any, attrs map[string]any) int64
UpdateExistingPivotOrFail 更新现存 pivot 行,失败 panic *FailError{Op:"updateExistingPivot"},返回受影响行数。
func (*Connection) UpdateModel ¶
func (c *Connection) UpdateModel(model any, attrs map[string]any) error
UpdateModel 模型级批量赋值更新(fill + save): Fill 走守卫规则,Save 的干净保存语义(无脏列不发 SQL)自动生效。 命名避开 Connection.Update(原生 SQL 方法),与 DestroyByIDs 先例一致。
func (*Connection) UpdateOrCreate ¶
func (c *Connection) UpdateOrCreate(model interface{}, attributes, values map[string]interface{}) error
UpdateOrCreate 按 attributes 查找;命中则更新 values,未命中则创建 (updateOrCreate(attributes, values) 语义:赋值走 fill 守卫语义)。
func (*Connection) UpdateQuietly ¶
func (c *Connection) UpdateQuietly(model any, attrs map[string]any) error
UpdateQuietly 批量赋值后静默保存(与 UpdateModel 一致走守卫 Fill)。
func (*Connection) UseWriteConnectionWhenReading ¶
func (c *Connection) UseWriteConnectionWhenReading(value ...bool)
UseWriteConnectionWhenReading 强制读语句走写连接(对应 useWriteConnectionWhenReading)。
func (*Connection) WhenQueryingForLongerThan ¶
func (c *Connection) WhenQueryingForLongerThan(thresholdMs int64, handler func(QueryExecuted))
WhenQueryingForLongerThan 当累计查询耗时超过 thresholdMs 毫秒时触发一次 handler(随附触发时的 QueryExecuted)。
func (*Connection) WithoutPretending ¶
func (c *Connection) WithoutPretending(fn func() error) error
WithoutPretending 在临时关闭 dry-run 的状态下执行回调(对应 Connection::withoutPretending):回调结束后恢复原 pretending 状态。
func (*Connection) WriteDB ¶
func (c *Connection) WriteDB() *sql.DB
WriteDB 返回主(写)句柄快照(connMu 保护;迁移锁等需要专用物理连接的 场景经 db.Conn 再取独占连接)。
type Connector ¶
type Connector interface {
// Connect 打开数据库连接(实现可在连接前对 DSN 做方言化增强/校验)。
Connect(dsn string) (*sql.DB, error)
}
Connector 数据库连接器接口:建立数据库连接。
type Cursor ¶
type Cursor struct {
// contains filtered or unexported fields
}
Cursor 游标:参数集合 + 方向标记, 编码为 base64(json)(url 安全:+ → -、/ → _、= 剔除)。
func CursorFromEncoded ¶
CursorFromEncoded 从编码串解码游标(对应 Cursor::fromEncoded;非法返回 nil)。
func (*Cursor) PointsToNextItems ¶
PointsToNextItems 游标是否指向后一页。
type CursorPaginator ¶
type CursorPaginator struct {
Items any
PerPage int64
HasMore bool
Cursor *Cursor
NextCursor *Cursor
PreviousCursor *Cursor
}
CursorPaginator 游标分页结果结构。
func (CursorPaginator) HasMorePages ¶
func (p CursorPaginator) HasMorePages() bool
HasMorePages 是否还有下一页(基于 nextCursor 是否非空判断)。
func (CursorPaginator) Parameter ¶
func (p CursorPaginator) Parameter(name string) any
Parameter 取当前游标参数(转发 Cursor.Parameter:无游标返回 nil; 有游标但缺参时沿用 Cursor.Parameter 的 panic 语义)。
func (CursorPaginator) PointsToNextItems ¶
func (p CursorPaginator) PointsToNextItems() bool
PointsToNextItems 当前游标是否指向后一页(转发 Cursor 同名方法; 无游标返回 false)。
type Dispatcher ¶
type Dispatcher = events.Dispatcher
Event / ModelEvent / Dispatcher / EventBus / QueryExecuted:类型别名(兼容层)。
type ErrInvalid ¶
type ErrInvalid struct{ Msg string }
ErrInvalid 参数无效错误(无效参数异常)。
func (ErrInvalid) Error ¶
func (e ErrInvalid) Error() string
type ErrMultiple ¶
type ErrMultiple struct{ Msg string }
ErrMultiple 记录命中多行错误(sole 期望单行时命中多行)。
func (ErrMultiple) Error ¶
func (e ErrMultiple) Error() string
type ErrNotFound ¶
type ErrNotFound struct{ Msg string }
ErrNotFound 记录未找到错误(firstOrFail/sole 未命中)。
func (ErrNotFound) Error ¶
func (e ErrNotFound) Error() string
type Error ¶
Error 携带 SQL 与分类的查询错误(查询异常包装)。
type Factory ¶
type Factory[T any] struct { Definition func(seq int) T Table string // 可选:批量插入的表名(Create 用 Create 生命周期则不需要) // contains filtered or unexported fields }
Factory 模型工厂:Definition 按 1 起始的序号生成模型。 T 为模型指针类型(如 *Post)以支持 Create 走完整生命周期。
func (Factory[T]) AfterCreating ¶
AfterCreating 注册落库成功后的钩子(afterCreating; 此时主键已回填)。
func (Factory[T]) AfterMaking ¶
AfterMaking 注册 make 生命周期钩子(afterMaking)。
func (Factory[T]) Create ¶
func (f Factory[T]) Create(conn *Connection, count int) ([]T, error)
Create 生成并落库:逐条走 Create 生命周期(时间戳/观察者/主键回填)。
func (Factory[T]) CreateMany ¶
func (f Factory[T]) CreateMany(conn *Connection) ([]T, error)
CreateMany 按 Count(n) 数量生成并落库(未设置时 1 个)。
func (Factory[T]) CreateOne ¶
func (f Factory[T]) CreateOne(conn *Connection) (T, error)
CreateOne 生成单个模型并落库(createOne 语义)。
func (Factory[T]) For ¶
For 注册 belongsTo 父模型:make/create 时把 parent 主键写入外键列 (外键缺省 = singular(parent 表名)_id)。
func (Factory[T]) SequenceAttrs ¶
SequenceAttrs 属性 map 形态的轮换序列(每个 map 为一轮属性)。
type Field ¶
type Field struct {
Value reflect.Value
StructField reflect.StructField
Attrs map[string]string
Primary bool
Name string
Ignored bool
IsBlank bool
Cast string // 原始 cast 标签值(cast:json 等);cast:array 内部归一为 "json"
CastName string // cast 基名:json/date/datetime/decimal/bool/int/float/uuid/ulid
CastArg string // cast 参数(decimal:N 的 N 等)
UniqueID string // unique_id 生成类型:"uuid" / "ulid"(空 = 不生成)
}
Field The model field definition
func (*Field) ReadCast ¶
ReadCast 读取后转换:把扫描结果规范化为字段语义类型。
json cast 把字符串反序列化进结构体/切片(connection 层 holder 已完成时为 no-op); date cast 把 time.Time 截断到当天零点(asDate 语义); decimal cast 把字符串值规范化到指定精度。 读侧要求驱动返回时间值(MySQL parseTime=true 惯例),字符串列无法在扫描后补救。
func (*Field) WriteCast ¶
WriteCast 写入前转换:把字段 Go 值转为数据库绑定值。
cast:json / cast:array —— 结构体/切片/映射序列化为字符串;空值约定: nil/零值集合写 "[]"(空集合语义),零值结构体写 null。 cast:date / cast:datetime —— time.Time 按格式序列化(cast:datetime:Y-m-d 自定义, 否则全局默认 = 方言 GetDateFormat)。 cast:decimal:N —— 数字/字符串规范化为 N 位定点字符串。 cast:bool / cast:int / cast:float —— 规范化为对应标量。
type HasMany ¶
HasMany 一对多。
func (HasMany) GetResults ¶
func (r HasMany) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
GetResults 单父查询:按父键取关联集合(对应 HasMany::getResults)。
type HasManyThrough ¶
type HasManyThrough struct {
ThroughModel any
FirstKey string
SecondKey string
LocalKey string
SecondLocalKey string
TargetModel any
// WithTrashedParents 跳过中间表软删过滤(对应 withTrashedParents 语义;
// 默认:中间模型有 deleted_at 字段时 join 条件追加 deleted_at is null)
WithTrashedParents bool
}
HasManyThrough 远程一对多(经中间表)。 例:User HasManyThrough Comment,经 Post:
ThroughModel: Post{}; FirstKey: "user_id"(posts 上的父外键);
SecondKey: "post_id"(comments 上的中间表键); LocalKey: "id"; SecondLocalKey: "id"
func (HasManyThrough) GetResults ¶
func (r HasManyThrough) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
GetResults 单父查询:经中间表取远程关联(对应 HasManyThrough::getResults)。
func (HasManyThrough) WithTrashed ¶
func (r HasManyThrough) WithTrashed() HasManyThrough
WithTrashedParents 跳过中间模型软删过滤。
type HasOne ¶
type HasOne struct {
ForeignKey string // 目标表列
LocalKey string // 本表键(默认 id)
Model any
// withDefault(对应 SupportsDefaultModels,HasOne.php 亦实现):
// 关系未命中时返回目标模型新实例而非空;
// DefaultFn 非 nil 时以新实例调用,返回值非 nil 则使用之
HasDefault bool
DefaultFn func(inst any) any
// one-of-many 变体(对应 CanBeOneOfMany):OfManyColumn/OfManyAggregate
// 非空时 GetResults/预加载按该列取极值一行(latestOfMany → max(created_at)、
// oldestOfMany → min(created_at))。
OfManyColumn string
OfManyAggregate string // "max" | "min";空串 = 关闭
// Partial one() 显式标记:GetResults/预加载只取单行(对应
// SupportsPartialRelations::one();HasOne 本就单行,此标记使查询显式 limit 1)
Partial bool
}
HasOne 正向一对一:目标表持有外键。
func (HasOne) GetResults ¶
GetResults 单父查询:按父键取关联(对应 HasOne::getResults)。 one-of-many 时按极值列 + 主键 tie-break 排序取一行(对应 CanBeOneOfMany 的 row_number 子查询 join 语义);withDefault 生效时未命中返回默认实例。
func (HasOne) LatestOfMany ¶
LatestOfMany 取该列最新一行(对应 latestOfMany,缺省列 created_at)。
func (HasOne) OldestOfMany ¶
OldestOfMany 取该列最早一行(对应 oldestOfMany,缺省列 created_at)。
type HasOneThrough ¶
type HasOneThrough struct {
ThroughModel any
FirstKey string
SecondKey string
LocalKey string
SecondLocalKey string
TargetModel any
// WithTrashedParents 跳过中间表软删过滤(同 HasManyThrough)
WithTrashedParents bool
}
HasOneThrough 远程一对一(HasManyThrough 的 单行变体):键约定与 HasManyThrough 相同,仅取首条结果。 例:Mechanic HasOneThrough CarOwner(经 Car):
ThroughModel: Car{}; FirstKey: "mechanic_id"(cars 上的父外键);
SecondKey: "car_id"(owners 上的中间表键); LocalKey: "id"; SecondLocalKey: "id"
func (HasOneThrough) GetResults ¶
func (r HasOneThrough) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
GetResults 单父查询:经中间表取首条关联(对应 HasOneThrough::getResults = first() ?: default;父键为空时无默认实例直接返回空)。
func (HasOneThrough) WithTrashed ¶
func (r HasOneThrough) WithTrashed() HasOneThrough
WithTrashed 跳过中间模型软删过滤。
type LengthAwarePaginator ¶
type LengthAwarePaginator struct {
Items any
Total int64
PerPage int64
CurrentPage int64
LastPage int64
}
LengthAwarePaginator 长度感知分页结果结构。
func (LengthAwarePaginator) Appends ¶
func (p LengthAwarePaginator) Appends(query map[string]string) AppendedLengthAware
Appends 追加公共查询参数,返回携带参数的链式副本: 分页器结构体未存储查询参数字段,以包装副本 AppendedLengthAware 承载(内嵌类型转发其余方法)。
func (LengthAwarePaginator) FirstItem ¶
func (p LengthAwarePaginator) FirstItem() int
FirstItem 当前页首条目的全局序号(1 起): 当前页无条目时返回 0。
func (LengthAwarePaginator) From ¶
func (p LengthAwarePaginator) From() int
From 当前页起始条目序号(firstItem 别名)。
func (LengthAwarePaginator) HasMorePages ¶
func (p LengthAwarePaginator) HasMorePages() bool
HasMorePages 是否还有下一页。
func (LengthAwarePaginator) LastItem ¶
func (p LengthAwarePaginator) LastItem() int
LastItem 当前页末条目的全局序号:无条目返回 0。
func (LengthAwarePaginator) PageLinks ¶
func (p LengthAwarePaginator) PageLinks(onEachSide int) []int
PageLinks 页码窗口:首页 + 当前页 ±onEachSide + 尾页;首/尾页与窗口之间的缺口以 -1 表示省略号 (即 "...")。采用旧版窗口算法(输出为当前页±n + 首尾锚 + -1 省略号): 当前页 > onEachSide+2 时补前省略号,当前页 < 尾页-(onEachSide+1) 时 补后省略号。
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
DatabaseManager 具名连接管理器(连接复用 + 并发安全)。
func (*Manager) Connect ¶
func (m *Manager) Connect(name string) (*Connection, error)
Connect 获取具名连接实例;同一名称复用同一连接(*sql.DB 自带连接池)。 name 为空时使用默认连接;支持 "name::read" / "name::write" 读写路由。
func (*Manager) ConnectUsing ¶
ConnectUsing 以显式配置立即建立具名连接(对应 DatabaseManager::connectUsing)。 force 为 true 时先断开并替换同名既有连接;否则同名连接已存在时报错。
func (*Manager) Disconnect ¶
Disconnect 关闭具名连接并移出缓存,使后续 Connect 重新建立连接 (对应 DatabaseManager::disconnect;Go 侧 *sql.DB 关闭后不可复用, 故移出缓存以实现重连)。
func (*Manager) Extend ¶
func (m *Manager) Extend(driver string, resolver func(Config) (*Connection, error))
Extend 注册连接解析扩展(对应 DatabaseManager::extend):优先按连接名命中, 其次按驱动名。
func (*Manager) ForgetExtension ¶
ForgetExtension 移除连接解析扩展。
func (*Manager) GetConnections ¶
GetConnections 返回已创建连接的名称列表(对应 DatabaseManager::getConnections)。
func (*Manager) GetDefaultConnection ¶
GetDefaultConnection 返回默认连接名。
func (*Manager) Reconnect ¶
func (m *Manager) Reconnect(name string) (*Connection, error)
Reconnect 重连具名连接(对应 DatabaseManager::reconnect):与 Disconnect+ Connect 不同,保留同一 Connection 实例(连接名/事件/事务状态不丢),仅用 其配置重建底层句柄并重发 ConnectionEstablished;连接尚未建立时等价 Connect。
func (*Manager) SetDefaultConnection ¶
SetDefaultConnection 设置默认连接名(Connect("") 时使用)。
func (*Manager) SetEventDispatcher ¶
func (m *Manager) SetEventDispatcher(d events.Dispatcher)
SetEventDispatcher 挂载管理器级事件分发器:每次成功建立新连接后分发 ConnectionEstablished 事件(对应 DatabaseManager::dispatchConnectionEstablishedEvent)。
func (*Manager) SetReconnector ¶
func (m *Manager) SetReconnector(fn func(*Connection) error)
SetReconnector 设置重连回调:之后建立的连接将挂载该回调 (对应 DatabaseManager::setReconnector + configure 的接线;未设置时使用 默认回调,即 Manager.Reconnect 保留实例重建句柄)。
func (*Manager) Transaction ¶
Transaction 在具名连接上执行事务回调(转发 Connection::Transaction)。
type MassAssignmentError ¶
type MassAssignmentError struct {
Key string
}
MassAssignmentError 质量赋值异常: Fill 时试图写入被守卫的字段。
func (*MassAssignmentError) Error ¶
func (e *MassAssignmentError) Error() string
type Model ¶
type Model struct {
field.IDAttr
field.CreatedAtAttr
field.UpdatedAtAttr
field.ModelStateAttr
}
Model 是内嵌属性集合(兼容旧用法)。内嵌后除 id/created_at/updated_at 列外 还携带 ModelStateAttr:original/changes/exists 状态随实例存储, 长驻进程无需手动 ForgetModel(模型自持 original 状态随实例存活)。
type ModelEvent ¶
type ModelEvent = events.ModelEvent
Event / ModelEvent / Dispatcher / EventBus / QueryExecuted:类型别名(兼容层)。
type MorphCountSpec ¶
type MorphCountSpec struct {
Name string // 计数别名(对应 withCount('comments') → comments_count)
Relation Relation // 被计数的关系描述符
}
MorphCountSpec morphTo morphWithCount 的单条计数规格: morphWithCount([类型 => [关系名, ...]]) 的一项;原按关系名隐式解析, Go 侧无容器需显式给出关系描述符。
type MorphMany ¶
type MorphMany struct {
MorphName string // 多态名(决定默认列名 morphName_type / morphName_id)
MorphKey string
TypeColumn string
IDColumn string
TargetModel any
}
MorphMany 多态一对多:目标表持有 type 列(commentable_type)与 id 列(commentable_id)。 MorphKey 为类型列取值,缺省 = 父表名(Go 侧约定,非 FQCN 形态)。
func (MorphMany) GetResults ¶
func (r MorphMany) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
GetResults 单父查询:按父键 + 类型列取多态关联(对应 MorphMany::getResults)。
type MorphOne ¶
type MorphOne struct {
MorphName string
MorphKey string
TypeColumn string
IDColumn string
TargetModel any
// withDefault(对应 SupportsDefaultModels,HasOne.php 同款实现):
// 关系未命中时返回目标模型新实例而非 nil;DefaultFn 非 nil 时以新实例
// 调用,返回值非 nil 则使用之
HasDefault bool
DefaultFn func(inst any) any
// one-of-many 变体(对应 CanBeOneOfMany,语义同 HasOne 同名字段)
OfManyColumn string
OfManyAggregate string // "max" | "min";空串 = 关闭
Partial bool // one():显式标记只取单行
}
MorphOne 多态一对一。
func (MorphOne) GetResults ¶
func (r MorphOne) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
GetResults 单父查询:按父键 + 类型列取多态关联(对应 MorphOne::getResults)。 one-of-many 取极值一行(极值列 + 主键 tie-break 排序,对应 CanBeOneOfMany); withDefault 生效时未命中返回默认实例。
func (MorphOne) LatestOfMany ¶
LatestOfMany 取该列最新一行(对应 MorphOne::latestOfMany,缺省列 created_at)。
func (MorphOne) OldestOfMany ¶
OldestOfMany 取该列最早一行(对应 MorphOne::oldestOfMany,缺省列 created_at)。
type MorphTo ¶
type MorphTo struct {
MorphName string
TypeColumn string
IDColumn string
TypeMap map[string]any
// OwnerKey 目标表键(默认 id,对应 MorphTo $ownerKey)
OwnerKey string
// WithTrashed 目标模型为软删时跳过 deleted_at 过滤(对应 morphTo withTrashed)
WithTrashed bool
// OnlyTrashed 仅取已软删的 owner(对应 morphTo onlyTrashed;描述符级变体,
// 预加载级变体见 Builder.MorphToOnlyTrashed)
OnlyTrashed bool
// withDefault(对应 SupportsDefaultModels):关系未命中时返回空实例而非 nil;
// DefaultFn 非 nil 时以新实例调用,返回值非 nil 则使用之
HasDefault bool
DefaultFn func(inst any) any
}
MorphTo 反向多态:本表持有类型列与 id 列;TypeMap 把类型串映射到模型零值。
func (MorphTo) GetResults ¶
func (r MorphTo) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
GetResults 单父查询:按类型列解析目标模型后取 owner(对应 MorphTo::getResults)。 MorphName/TypeColumn 均空时从父模型 schema 推断(唯一 *_type 列)。
func (MorphTo) WithDefault ¶
WithDefault 启用默认模型(对应 SupportsDefaultModels::withDefault): 关系未命中时返回默认实例而非 nil。Go 侧 MorphTo 描述符无解析出的目标 类型(targetModel 为 nil),无回调时仅在类型已解析(行存在但查询未命中) 的情况下能以 TypeMap 的零值类型实例化;类型列也为空时必须提供回调 构造实例(fn 的 inst 参可能为 nil)。返回值非 nil 时使用返回值。
func (MorphTo) WithDeleted ¶
WithDeleted 跳过目标模型软删过滤(对应 withTrashed 的链式形态)。
func (MorphTo) WithOnlyTrashed ¶
WithOnlyTrashed 仅取已软删的 owner(对应 onlyTrashed 的链式形态)。
type MorphToMany ¶
type MorphToMany struct {
RelatedModel any
MorphName string
MorphKey string // 类型列取值(缺省 = 父表名)
Table string // 缺省 = plural(morphName)
TypeColumn string // 缺省 morphName_type
ForeignPivotKey string // 缺省 morphName_id(本表在 pivot 的键)
RelatedPivotKey string // 缺省 目标单数_id
RelatedKey string // 缺省 id
}
MorphToMany 多态多对多: pivot 表(缺省 = morphName 的复数,如 taggable → taggables)持有 morphName_type / morphName_id 与目标表外键(目标单数_id)。
func (MorphToMany) GetResults ¶
func (r MorphToMany) GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
GetResults 单父查询:经 pivot 表按类型列取多态多对多关联。
type MorphedByMany ¶
type MorphedByMany = MorphToMany
MorphedByMany 反向多态多对多: 与 morphToMany 共用同一 pivot 表,仅语义方向相反。
type MySqlConnector ¶
type MySqlConnector struct {
// contains filtered or unexported fields
}
MySqlConnector MySQL 连接器(对应 Connectors\MySqlConnector):校验 DSN 并 自动附加 charset/collation/sql_mode/timezone/parseTime 参数(来自 Config, 已有参数不覆盖);隔离级别经 driver.Connector 包装在每个物理连接上生效。
func (*MySqlConnector) BuildDsn ¶
func (c *MySqlConnector) BuildDsn(dsn string) string
BuildDsn 校验(非标准 DSN 原样返回,交给驱动在连接时报错)并增强 DSN。
type Observer ¶
type Observer struct {
Retrieving func(model any) error // 水合前触发,返回 error 取消该行水合(行保持扫描零值仍留在结果中,其他实现为不进结果集)
Retrieved func(model any)
Saving func(model any) error
Saved func(model any) error
Creating func(model any) error
Created func(model any) error
Updating func(model any) error
Updated func(model any) error
Deleting func(model any) error
Deleted func(model any) error
Trashed func(model any) error
ForceDeleting func(model any) error
Restoring func(model any) error
Restored func(model any) error
Replicating func(model any) error
ForceDeleted func(model any) error
}
Observer 模型观察者:按模型类型注册可选回调。 回调返回 error 时中断当前操作(异常中断生命周期)。
type PivotRelation ¶
type PivotRelation interface {
Relation
// contains filtered or unexported methods
}
PivotRelation belongsToMany / morphToMany 的 pivot 写侧关系接口。
type PivotScopeCond ¶
PivotScopeCond wherePivot 族的单条条件(basic/in/notIn/between/notBetween/null/notNull)。
type PivotSpec ¶
type PivotSpec struct {
Pivot string // pivot 表名
FPK string // 父侧键列
RPK string // 目标侧键列
TypeCol string // 多态类型列(BTM 为空)
MorphKey string // 类型列取值(HasType 时有效)
HasType bool
Timestamps bool // attach/sync 更新时自动补 created_at/updated_at
// Attrs WithPivotValue 固定值(attach 属性打底;同时参与 sync/detach 范围)
Attrs map[string]any
// ScopeConds wherePivot 族条件(参与读取与 sync/detach 范围)
ScopeConds []PivotScopeCond
}
PivotSpec pivot 写侧归一规格。
type PostgresConnector ¶
type PostgresConnector struct {
// contains filtered or unexported fields
}
PostgresConnector Postgres 连接器(对应 Connectors\PostgresConnector): 自动附加 sslmode/search_path/timezone DSN 参数;isolation_level/ synchronous_commit 经 DSN options=-c 参数生效(连接池下每个物理连接 均有效——libpq 标准参数,lib/pq 支持)。
func (*PostgresConnector) BuildDsn ¶
func (c *PostgresConnector) BuildDsn(dsn string) string
BuildDsn 附加 sslmode/sslcert/sslkey/sslrootcert/search_path/client_encoding/ application_name/TimeZone/options 参数(已有参数不覆盖)。
type QueryExecuted ¶
type QueryExecuted = events.QueryExecuted
Event / ModelEvent / Dispatcher / EventBus / QueryExecuted:类型别名(兼容层)。
type RawQueryLog ¶
RawQueryLog 绑定插值后的查询日志条目(对应 getRawQueryLog 的 raw_query/time)。
type Relation ¶
type Relation interface {
// GetResults 单父查询:
// 返回关联模型指针(*T)切片;无关联时返回空切片。
GetResults(parent any, c *Connection, constraints ...func(*Builder)) ([]any, error)
// contains filtered or unexported methods
}
Relation 关系定义(约定关系两侧的键命名)。
type SQLiteConnector ¶
type SQLiteConnector struct {
// contains filtered or unexported fields
}
SQLiteConnector SQLite 连接器(对应 Connectors\SQLiteConnector):全部 pragmas 经驱动 DSN 参数生效(_foreign_keys/_busy_timeout/_journal_mode/ _synchronous/_pragma)——连接池下每个物理连接均生效;旧实现自定义 pragmas 用 db.Exec 只落在池内随机一个连接上。
func (*SQLiteConnector) BuildDsn ¶
func (c *SQLiteConnector) BuildDsn(dsn string) string
BuildDsn 附加 sqlite pragma 参数。foreign_keys 缺省开启 (与 SQLite 默认 foreign_keys=true 对齐;显式 false 可关闭)。
type Schema ¶
type Schema struct {
Fields []*Field
PrimaryField *Field
// contains filtered or unexported fields
}
Schema model definition
func NewSchema ¶
NewSchema 反射解析模型结构为字段列表:
- 跳过未导出字段(旧实现对未导出字段 Addr().Interface() 会 panic);
- 内嵌(anonymous)结构体字段扁平化为其子字段(子字段保留自身 tag), 使 field.IDAttr / torm.Model / SoftDeletes 等基座可用;
- 带 torm tag 的内嵌字段按原语义视为普通列。
func (*Schema) Attributes ¶
type SchemaBuilder ¶
type SchemaBuilder struct {
// contains filtered or unexported fields
}
SchemaBuilder 为 Schema 构建器门面(挂在具名连接上)。
func (*SchemaBuilder) AlterTable ¶
func (s *SchemaBuilder) AlterTable(table string, fn func(t *grammar.Blueprint)) error
AlterTable 兼容别名(= Table,修改表)。
func (*SchemaBuilder) Create ¶
func (s *SchemaBuilder) Create(table string, fn func(t *grammar.Blueprint)) error
Create 新建表(Blueprint 处于 create 模式)。
func (*SchemaBuilder) CreateDatabase ¶
func (s *SchemaBuilder) CreateDatabase(name string) error
CreateDatabase 创建数据库。
func (*SchemaBuilder) CreateTable ¶
func (s *SchemaBuilder) CreateTable(table string, fn func(t *grammar.Blueprint)) error
CreateTable 兼容别名(= Create,新建表)。
func (*SchemaBuilder) DisableForeignKeyConstraints ¶
func (s *SchemaBuilder) DisableForeignKeyConstraints() error
DisableForeignKeyConstraints 禁用外键约束。
func (*SchemaBuilder) DropAllTables ¶
func (s *SchemaBuilder) DropAllTables() error
DropAllTables 删除当前 schema 下全部表。 MySQL/PG:外键开关包裹 + 逐表 drop(对应 MySqlBuilder/PostgresBuilder); SQLite:writable_schema + sqlite_master delete + vacuum(SQLiteBuilder::dropAllTables, 统一走 writable_schema 路径保证连接内一致;文件级清空 TODO 接线点: 按 DSN 判定文件库后 os.Truncate); SQL Server:先 drop 全部外键,再 sp_msforeachtable(SqlServerBuilder::dropAllTables)。
func (*SchemaBuilder) DropAllTypes ¶
func (s *SchemaBuilder) DropAllTypes() error
DropAllTypes 删除当前 schema 下全部用户自定义类型(仅 Postgres 支持, 其余驱动对应基类的 LogicException 语义)。
func (*SchemaBuilder) DropAllViews ¶
func (s *SchemaBuilder) DropAllViews() error
DropAllViews 删除当前 schema 下全部视图。
func (*SchemaBuilder) DropColumns ¶
func (s *SchemaBuilder) DropColumns(table string, columns ...string) error
DropColumns 删除列(对应 Builder.php:560 dropColumns)。统一走各方言 grammar 的 CompileDropColumn(Blueprint 编译路径): SQLite 产出合法的 alter table x drop column y (>= 3.35,避免缺 COLUMN 关键字的方言非法 SQL);SQL Server 含默认约束 前置块;方言不支持时返回明确错误(RuntimeException 对应物)。
func (*SchemaBuilder) DropDatabaseIfExists ¶
func (s *SchemaBuilder) DropDatabaseIfExists(name string) error
DropDatabaseIfExists 条件删除数据库。
func (*SchemaBuilder) DropIfExists ¶
func (s *SchemaBuilder) DropIfExists(table string) error
DropIfExists 条件删表。
func (*SchemaBuilder) EnableForeignKeyConstraints ¶
func (s *SchemaBuilder) EnableForeignKeyConstraints() error
EnableForeignKeyConstraints 启用外键约束。
func (*SchemaBuilder) GetColumnListing ¶
func (s *SchemaBuilder) GetColumnListing(table string) ([]string, error)
GetColumnListing 列名列表。
func (*SchemaBuilder) GetColumnType ¶
func (s *SchemaBuilder) GetColumnType(table, column string) (string, error)
GetColumnType 返回列的完整类型(对应 getColumnType 的 fullDefinition 分支); 列不存在时报错(InvalidArgumentException 语义)。
func (*SchemaBuilder) GetColumns ¶
func (s *SchemaBuilder) GetColumns(table string) ([]SchemaColumn, error)
GetColumns 返回表列元数据(name/type_name/type/nullable/default/ autoincrement/comment)。
func (*SchemaBuilder) GetForeignKeys ¶
func (s *SchemaBuilder) GetForeignKeys(table string) ([]SchemaForeignKey, error)
GetForeignKeys 返回表外键元数据。
func (*SchemaBuilder) GetIndexListing ¶
func (s *SchemaBuilder) GetIndexListing(table string) ([]string, error)
GetIndexListing 返回索引名列表。
func (*SchemaBuilder) GetIndexes ¶
func (s *SchemaBuilder) GetIndexes(table string) ([]SchemaIndex, error)
GetIndexes 返回表索引元数据。
func (*SchemaBuilder) GetTableListing ¶
func (s *SchemaBuilder) GetTableListing(schema ...string) ([]string, error)
GetTableListing 返回当前连接的表名列表(不含视图)。
func (*SchemaBuilder) GetTables ¶
func (s *SchemaBuilder) GetTables(schema ...string) ([]SchemaTable, error)
GetTables 返回当前连接的表元数据(结果过滤视图;可传 schema 收窄范围)。
func (*SchemaBuilder) GetTypes ¶
func (s *SchemaBuilder) GetTypes(schema ...string) ([]SchemaType, error)
GetTypes 返回用户自定义类型元数据(仅 Postgres;其余驱动不支持)。
func (*SchemaBuilder) GetViews ¶
func (s *SchemaBuilder) GetViews(schema ...string) ([]SchemaView, error)
GetViews 返回视图元数据(可传 schema 收窄范围)。
func (*SchemaBuilder) HasColumn ¶
func (s *SchemaBuilder) HasColumn(table, column string) (bool, error)
HasColumn 列是否存在(大小写不敏感)。
func (*SchemaBuilder) HasColumns ¶
func (s *SchemaBuilder) HasColumns(table string, columns []string) (bool, error)
HasColumns 全部列都存在才返回 true(对应 hasColumns 的 array_all 语义)。
func (*SchemaBuilder) HasForeignKey ¶
func (s *SchemaBuilder) HasForeignKey(table string, foreignKey any) (bool, error)
HasForeignKey 表是否拥有指定外键:foreignKey 可传外键名(string)或列集 ([]string)。
func (*SchemaBuilder) HasIndex ¶
HasIndex 表是否拥有指定索引:index 可传索引名(string)或列集([]string); typ 可选 "primary"/"unique"/方言类型名(对应 hasIndex 的 $type 过滤)。
func (*SchemaBuilder) HasTable ¶
func (s *SchemaBuilder) HasTable(table string) (bool, error)
HasTable 表是否存在(引用支持 schema.table 拆分)。
func (*SchemaBuilder) HasView ¶
func (s *SchemaBuilder) HasView(view string) (bool, error)
HasView 视图是否存在(大小写不敏感,引用支持 schema.table 拆分)。
func (*SchemaBuilder) Rename ¶
func (s *SchemaBuilder) Rename(from, to string) error
Rename 重命名表(对应 Builder.php:610 rename)。走各方言 grammar 的 CompileRename(MySQL rename table ... to ...、SQL Server sp_rename、 PG/SQLite alter table ... rename to ...),方言不支持时返回明确错误。
func (*SchemaBuilder) Statement ¶
func (s *SchemaBuilder) Statement(query string, args ...any) error
Statement 在连接上执行原生 SQL(Builder::statement 语义)。 供 SQL 文件迁移等无 Blueprint 场景使用;多语句文件要求驱动支持单次 Exec 执行多语句(MySQL 需 DSN multiStatements=true,SQLite 原生支持)。 Statement 执行原生 SQL(SQL 文件迁移的执行通道)。 **无参数时绕过预编译、直走连接级 Exec**:SQLite(mattn)与 MySQL (multiStatements=true)只在连接级 Execer 路径处理多语句脚本, 预编译路径只执行首条且余下语句被静默丢弃(已实证)。
func (*SchemaBuilder) Table ¶
func (s *SchemaBuilder) Table(table string, fn func(t *grammar.Blueprint)) error
Table 修改表(Blueprint 处于 alter 模式)。
func (*SchemaBuilder) WhenTableDoesntHaveColumn ¶
func (s *SchemaBuilder) WhenTableDoesntHaveColumn(table, column string, fn func(t *grammar.Blueprint)) error
WhenTableDoesntHaveColumn 表缺少指定列时执行表构建回调。
func (*SchemaBuilder) WhenTableDoesntHaveIndex ¶
func (s *SchemaBuilder) WhenTableDoesntHaveIndex(table string, index any, fn func(t *grammar.Blueprint), typ ...string) error
WhenTableDoesntHaveIndex 表缺少指定索引时执行表构建回调。
func (*SchemaBuilder) WhenTableHasColumn ¶
func (s *SchemaBuilder) WhenTableHasColumn(table, column string, fn func(t *grammar.Blueprint)) error
WhenTableHasColumn 表拥有指定列时执行表构建回调。
func (*SchemaBuilder) WhenTableHasIndex ¶
func (s *SchemaBuilder) WhenTableHasIndex(table string, index any, fn func(t *grammar.Blueprint), typ ...string) error
WhenTableHasIndex 表拥有指定索引(名称或列集,可选类型过滤)时执行表构建回调。
func (*SchemaBuilder) WithoutForeignKeyConstraints ¶
func (s *SchemaBuilder) WithoutForeignKeyConstraints(fn func() error) error
WithoutForeignKeyConstraints 在回调执行期间禁用外键约束(无论成败都恢复)。
type SchemaColumn ¶
type SchemaColumn struct {
Name string
TypeName string // 基础类型名(如 varchar / int4)
Type string // 完整类型(如 varchar(255))
Nullable bool
Default any
AutoIncrement bool
Comment string
}
SchemaColumn 内省结果:表列元数据(getColumns 返回的行结构)。
type SchemaForeignKey ¶
type SchemaForeignKey struct {
Name string
Columns []string
ForeignSchema string
ForeignTable string
ForeignColumns []string
OnUpdate string
OnDelete string
}
SchemaForeignKey 内省结果:外键元数据(对应 getForeignKeys 行结构)。
type SchemaIndex ¶
type SchemaIndex struct {
Name string
Columns []string
Type string // btree / hash 等(方言相关)
Unique bool
Primary bool
}
SchemaIndex 内省结果:索引元数据(对应 getIndexes 行结构)。
type SchemaTable ¶
type SchemaTable struct {
Name string
Schema string
Size int64
Comment string
Engine string
Collation string
}
SchemaTable 内省结果:表元数据(对应 getTables 行结构)。
type SchemaType ¶
type SchemaType struct {
Name string
Schema string
Type string // typtype:c(composite)/e(enum)/d(domain)/m(range) 等
Category string // typcategory
Implicit bool
}
SchemaType 内省结果:用户自定义类型元数据(对应 getTypes 行结构,仅 Postgres)。
type SchemaView ¶
SchemaView 内省结果:视图元数据(对应 getViews 行结构)。
type SerializeOptions ¶
SerializeOptions 控制单次序列化的隐藏/可见列(实例级语义——类型级 MakeHidden/MakeVisible 之外的一次性覆盖,临时 makeHidden 形态)。
func WithHidden ¶
func WithHidden(keys ...string) SerializeOptions
WithHidden 追加隐藏列的选项(makeHidden 的临时形态)。
func WithVisible ¶
func WithVisible(keys ...string) SerializeOptions
WithVisible 仅输出指定列(makeVisible / visible 的临时形态)。
type SimplePaginator ¶
SimplePaginator 简单分页结果结构(多取一条判断 hasMore)。
func (SimplePaginator) Appends ¶
func (p SimplePaginator) Appends(query map[string]string) AppendedSimple
Appends 追加公共查询参数,返回携带参数的链式副本。
func (SimplePaginator) FirstItem ¶
func (p SimplePaginator) FirstItem() int
FirstItem 当前页首条目的全局序号(简单分页器 同样具备;无条目返回 0)。
func (SimplePaginator) HasMorePages ¶
func (p SimplePaginator) HasMorePages() bool
HasMorePages 是否还有下一页(基于 simplePaginate 多取一条判断出的 HasMore)。
func (SimplePaginator) LastItem ¶
func (p SimplePaginator) LastItem() int
LastItem 当前页末条目的全局序号:无条目返回 0。
type SqlServerConnector ¶
type SqlServerConnector struct {
// contains filtered or unexported fields
}
SqlServerConnector SQLServer 连接器(对应 Connectors\SqlServerConnector)。 注意:go-mssqldb 的 DSN 不支持隔离级别参数,isolation_level 仍以建连后 SET 执行——连接池下仅对执行时选中的连接生效(已知限制,需要精确控制时 建议在事务内显式 set transaction isolation level)。
type SyncResult ¶
SyncResult sync 的返回(attached/detached/updated 三组)。
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
driver
|
|
|
Package events 数据库层事件包: 查询与模型生命周期事件对象、分发器接口与默认总线实现。
|
Package events 数据库层事件包: 查询与模型生命周期事件对象、分发器接口与默认总线实现。 |
|
internal
|
|
|
faketb
Package faketb provides an in-memory fake database/sql driver so the torm test suites can exercise the connection layer without a real MySQL server.
|
Package faketb provides an in-memory fake database/sql driver so the torm test suites can exercise the connection layer without a real MySQL server. |