@orieljs/database 0.1.0-alpha.14 → 0.1.0-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { OrielError, ModelNotFoundError as ModelNotFoundError$1, DriverName, DatabaseConnection, Row, QueryBuilder, Operator, DatabaseManager, Token, ModelInstance, DatabaseNotification as DatabaseNotification$1, Application, ConsoleKernel, RouteModelResolver, Class } from '@orieljs/contracts';
1
+ import { OrielError, ModelNotFoundError as ModelNotFoundError$1, DriverName, DatabaseConnection, Row, Operator, ModelInstance, QueryBuilder, DatabaseManager, Token, DatabaseNotification as DatabaseNotification$1, Application, ConsoleKernel, RouteModelResolver, Class } from '@orieljs/contracts';
2
2
  import { SqliteDatabase, SqliteStatement, Dialect, RawBuilder, Kysely, CompiledQuery, QueryResult } from 'kysely';
3
3
  import { Collection, LazyCollection, Operator as Operator$1 } from '@orieljs/collections';
4
4
  import * as _orieljs_support from '@orieljs/support';
5
5
  import { ServiceProvider } from '@orieljs/support';
6
+ export { serializeDate } from '@orieljs/support';
6
7
 
7
8
  /** Thrown by findOrFail()/firstOrFail() and route model binding. Renders as 404. */
8
9
  declare class ModelNotFoundError extends Error implements ModelNotFoundError$1 {
@@ -600,6 +601,7 @@ declare class Connection implements DatabaseConnection {
600
601
  protected readonly db: Kysely<any>;
601
602
  private readonly context;
602
603
  private readonly pinned;
604
+ private savepoints;
603
605
  private loggingQueries;
604
606
  private queryLog;
605
607
  constructor(name: string, config: ConnectionConfig);
@@ -607,9 +609,9 @@ declare class Connection implements DatabaseConnection {
607
609
  getDriverName(): DriverName;
608
610
  getConfig(): ConnectionConfig;
609
611
  /** A query builder for a table: connection.table('users').where('votes', '>', 100).get(). */
610
- table<T = Row>(table: string | Expression): Builder$1<T>;
612
+ table<T = Row>(table: string | Expression): Builder<T>;
611
613
  /** A query builder with no table yet (use from()). */
612
- query<T = Row>(): Builder$1<T>;
614
+ query<T = Row>(): Builder<T>;
613
615
  /** Schema operations on this connection (Laravel's getSchemaBuilder()). */
614
616
  getSchemaBuilder(): SchemaBuilder;
615
617
  /** Raw Kysely access. Inside a transaction this is the transaction, so queries join it. */
@@ -629,10 +631,34 @@ declare class Connection implements DatabaseConnection {
629
631
  private raw;
630
632
  /** Runs fn in a transaction (a savepoint when nested). Commits when fn resolves, rolls back and rethrows when it throws. */
631
633
  transaction<R>(fn: (connection: this) => Promise<R>): Promise<R>;
634
+ /** A committed level hands its callbacks to the transaction(fn) it's nested in, or runs them, outside its context. */
635
+ private committed;
636
+ /** A level that rolled back drops its callbacks and runs its onRollBack ones, outside its context. */
637
+ private rolledBack;
638
+ /** An onRollBack callback's failure must not hide the error that rolled the transaction back. */
639
+ private runQuietly;
632
640
  /** Starts a transaction that stays open, for every async context, until commit()/rollBack(). */
633
641
  beginTransaction(): Promise<void>;
642
+ /**
643
+ * @internal RefreshDatabase's and DatabaseTransactions': the level beginTransaction() just opened holds no
644
+ * afterCommit() callbacks, so they run as they would without the test's transaction (Laravel's
645
+ * callbacksShouldIgnore()), and a test's own transaction(fn) or beginTransaction() runs them at its commit.
646
+ */
647
+ ignoreAfterCommitAtCurrentLevel(): void;
648
+ /**
649
+ * Laravel's DB::afterCommit(): runs the callback once the transaction open here commits, the outermost one when
650
+ * they're nested, and drops it if that level rolls back: a transaction(fn) open in this async context, or a level
651
+ * beginTransaction() opened. Outside one, or in only the testing traits' transaction, it runs at once.
652
+ * `onRollBack` runs instead when the level that holds the callback rolls back. A callback added once its level has
653
+ * ended (by work nobody awaited) follows it: held by the level it was committed into, run if the commit is done,
654
+ * dropped if it rolled back.
655
+ */
656
+ afterCommit(callback: () => unknown, onRollBack?: () => unknown): Promise<void>;
657
+ /** @internal Whether a transaction is open here that afterCommit() would wait for. */
658
+ inTransactionContext(): boolean;
659
+ /** Commits the innermost level opened by beginTransaction(), then runs (or hands up) its afterCommit() callbacks. */
634
660
  commit(): Promise<void>;
635
- /** Rolls back the innermost level opened by beginTransaction(). Does nothing when none is open. */
661
+ /** Rolls back the innermost level opened by beginTransaction(), dropping its afterCommit() callbacks. */
636
662
  rollBack(): Promise<void>;
637
663
  transactionLevel(): number;
638
664
  enableQueryLog(): void;
@@ -646,125 +672,31 @@ declare class Connection implements DatabaseConnection {
646
672
  private close;
647
673
  }
648
674
 
649
- interface PaginatorOptions {
650
- /** The base URL of the page links (default: the current request's URL, or '/'). */
651
- path?: string;
652
- /** Extra query string values added to every link. */
653
- query?: Record<string, unknown>;
654
- fragment?: string;
655
- pageName?: string;
656
- }
657
- /** Laravel's Arr::query(): nested values become key[0]=…, encoded as RFC 3986. */
658
- declare function buildQuery(values: Record<string, unknown>, prefix?: string): string;
659
675
  /**
660
- * Shared paginator state and URL building (Laravel's AbstractPaginator).
661
- * The static resolvers read the current request; DatabaseServiceProvider points them at HttpRequest.
676
+ * A custom cast (Laravel's CastsAttributes): get() turns the stored value into what the model exposes, set() turns
677
+ * an assigned value back into what is stored.
662
678
  */
663
- declare abstract class AbstractPaginator<T> implements Iterable<T> {
664
- protected readonly perPageValue: number;
665
- static currentPathResolver: () => string;
666
- static currentPageResolver: (pageName: string) => number;
667
- static queryStringResolver: () => Record<string, unknown>;
668
- static currentCursorResolver: (cursorName: string) => unknown;
669
- static resolveCurrentPath(): string;
670
- static resolveCurrentPage(pageName?: string): number;
671
- /** Restores the defaults (page 1, path '/'). Used by tests and when the provider is torn down. */
672
- static resetResolvers(): void;
673
- protected collection: Collection<T>;
674
- protected pathValue: string;
675
- protected queryValues: Record<string, unknown>;
676
- protected fragmentValue: string | undefined;
677
- protected pageName: string;
678
- /** The resolved page number: page-based paginators pass it in; cursor pagination never reads it. */
679
- protected readonly currentPageValue: number;
680
- onEachSideCount: number;
681
- protected constructor(items: Iterable<T>, perPageValue: number, options: PaginatorOptions, currentPage?: number);
682
- currentPage(): number;
683
- /** The 1-based position of the first item on this page, or null when the page is empty. */
684
- firstItem(): number | null;
685
- lastItem(): number | null;
686
- onFirstPage(): boolean;
687
- previousPageUrl(): string | null;
688
- /** The URL for a page number: path?query&page=n#fragment. */
689
- url(page: number): string;
690
- protected buildFragment(): string;
691
- path(): string;
692
- withPath(path: string): this;
693
- setPath(path: string): this;
694
- /** Adds values to every link's query string. */
695
- appends(key: string | Record<string, unknown>, value?: unknown): this;
696
- /** Keeps the current request's query string on every link. */
697
- withQueryString(): this;
698
- fragment(fragment: string): this;
699
- getPageName(): string;
700
- setPageName(name: string): this;
701
- onEachSide(count: number): this;
702
- /** The items on this page, as an array (Laravel's items()). */
703
- items(): T[];
704
- getCollection(): Collection<T>;
705
- setCollection(items: Collection<T>): this;
706
- /**
707
- * Transforms each item in place, typically for serialization, and returns this paginator typed with the new items:
708
- * `posts.through((post) => ({ id: post.id }))`. Each paginator narrows the return type to its own class.
709
- */
710
- through<U>(callback: (item: T, index: number) => U): AbstractPaginator<U>;
711
- perPage(): number;
712
- count(): number;
713
- isEmpty(): boolean;
714
- isNotEmpty(): boolean;
715
- [Symbol.iterator](): Iterator<T>;
716
- protected itemsToArray(): unknown[];
717
- abstract toArray(): Record<string, unknown>;
718
- toJSON(): Record<string, unknown>;
719
- toJson(): string;
720
- }
721
-
722
- /** A position in a cursor-paginated result: the ordered columns' values of an edge item, plus the direction. */
723
- declare class Cursor {
724
- protected readonly parameters: Record<string, unknown>;
725
- protected readonly pointsToNext: boolean;
726
- constructor(parameters: Record<string, unknown>, pointsToNext?: boolean);
727
- parameter(name: string): unknown;
728
- pointsToNextItems(): boolean;
729
- pointsToPreviousItems(): boolean;
730
- toArray(): Record<string, unknown>;
731
- /** URL-safe base64 of the JSON parameters (Laravel's format). */
732
- encode(): string;
733
- /** Decodes a cursor from the query string. Anything malformed gives undefined (the first page). */
734
- static fromEncoded(encoded: unknown): Cursor | undefined;
735
- }
736
- interface CursorPaginatorOptions extends Omit<PaginatorOptions, 'pageName'> {
737
- cursorName?: string;
738
- /** The ordered columns whose values make up each cursor. */
739
- parameters: string[];
679
+ interface CastsAttributes<TGet = unknown, TSet = TGet> {
680
+ get(model: object, key: string, value: unknown, attributes: Row): TGet;
681
+ set(model: object, key: string, value: TSet, attributes: Row): unknown;
740
682
  }
683
+ /** A TypeScript enum object (string or numeric) used as a cast: casts = { status: PostStatus }. */
684
+ type EnumLike = Record<string, string | number>;
685
+ type BuiltInCast = 'int' | 'integer' | 'float' | 'double' | 'real' | 'string' | 'bool' | 'boolean' | 'array' | 'json' | 'object' | 'collection' | 'date' | 'datetime' | 'immutable_date' | 'immutable_datetime' | 'timestamp' | 'hashed' | `decimal:${number}`;
686
+ type CastDefinition = BuiltInCast | EnumLike | CastsAttributes | (new () => CastsAttributes);
687
+ /** The values of a TypeScript enum. Numeric enums also map values back to names; those reverse entries are skipped. */
688
+ declare function enumValues(cast: EnumLike): Array<string | number>;
689
+ declare const isJsonCast: (cast: CastDefinition | undefined) => boolean;
690
+ declare const isDateCast: (cast: CastDefinition | undefined) => boolean;
691
+ /** Laravel's castAttribute(): the stored value → the value the model exposes. null stays null (except custom casts). */
692
+ declare function castGet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
693
+ /** The value assigned to a cast attribute → the value stored in the model's attributes (and later bound). */
694
+ declare function castSet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
741
695
  /**
742
- * cursorPaginate(): "next"/"previous" by the ordered columns' values instead of an offset, so it stays fast and
743
- * stable on large, changing tables (Laravel's CursorPaginator). JSON: data, path, per_page, next_cursor,
744
- * next_page_url, prev_cursor, prev_page_url.
696
+ * Laravel's originalIsEquivalent(): does the stored value still mean the same thing as the original?
697
+ * Keeps save() from writing columns whose value only changed representation (1 vs true, '5' vs 5, same instant).
745
698
  */
746
- declare class CursorPaginator<T> extends AbstractPaginator<T> {
747
- protected readonly cursorValue: Cursor | undefined;
748
- protected readonly hasMore: boolean;
749
- protected readonly cursorName: string;
750
- protected readonly parameters: string[];
751
- constructor(items: Iterable<T>, perPage: number, cursorValue: Cursor | undefined, options: CursorPaginatorOptions);
752
- /** The cursor in the current request's query string (?cursor=…), if any. */
753
- static resolveCurrentCursor(cursorName?: string): Cursor | undefined;
754
- cursor(): Cursor | undefined;
755
- getCursorName(): string;
756
- through<U>(callback: (item: T, index: number) => U): CursorPaginator<U>;
757
- hasMorePages(): boolean;
758
- onFirstPage(): boolean;
759
- nextCursor(): Cursor | undefined;
760
- previousCursor(): Cursor | undefined;
761
- nextPageUrl(): string | null;
762
- previousPageUrl(): string | null;
763
- /** The URL for a cursor: path?query&cursor=…#fragment. */
764
- url(cursor: Cursor | number): string;
765
- protected cursorFor(item: T, pointsToNext: boolean): Cursor;
766
- toArray(): Record<string, unknown>;
767
- }
699
+ declare function isEquivalent(cast: CastDefinition | undefined, current: unknown, original: unknown, model: object, key: string, className: string): boolean;
768
700
 
769
701
  interface PaginationLink {
770
702
  url: string | null;
@@ -816,1729 +748,2096 @@ declare class Paginator<T> extends AbstractPaginator<T> {
816
748
  toArray(): Record<string, unknown>;
817
749
  }
818
750
 
819
- type Sql = RawBuilder<unknown>;
820
- /** The operators accepted by where()/having(). Anything else is rejected: operators are written into the SQL. */
821
- declare const OPERATORS: Set<string>;
751
+ declare const MANY: unique symbol;
752
+ /** Type-level marker set by count(): make()/create() then return the model's Eloquent collection. */
753
+ interface Many {
754
+ readonly [MANY]: true;
755
+ }
756
+ /** What make()/create() return: a model, or the model's Eloquent collection after count(), as Laravel's. */
757
+ type FactoryResult<F, M extends Model> = F extends Many ? EloquentCollection<M> : M;
758
+ /** What raw() returns: the attributes, or a list of them after count(). */
759
+ type RawResult<F> = F extends Many ? Row[] : Row;
760
+ /** Which model a state is being made for: its index in count() and the total. */
761
+ interface StateContext {
762
+ index: number;
763
+ count: number;
764
+ }
765
+ type State = Row | ((attributes: Row, context: StateContext) => Row);
766
+ type AnyFactory = Factory<any>;
822
767
  /**
823
- * Compiles a query builder's state into a Kysely `sql` template for one driver, like Laravel's Query\Grammars.
824
- * Identifiers go through sql.id() (quoted per dialect); values are always bound parameters.
768
+ * What has() and for() need from a factory: its model, create(), createOne() and state(). A factory of any model,
769
+ * counted or not, has them; Factory<any> itself would refuse a counted one, whose make(), create() and raw() return
770
+ * lists.
825
771
  */
826
- declare class Grammar {
827
- readonly driver: DriverName;
828
- constructor(driver: DriverName);
829
- /** 'users.name' → "users"."name", 'users.*' → "users".*, 'name as n' → "name" as "n". Expressions pass through raw. */
830
- wrap(value: string | Expression): Sql;
831
- wrapTable(table: string | Expression): Sql;
832
- prepare(value: unknown): unknown;
833
- /** A bound value, the raw SQL of an Expression, or a Kysely sql fragment as-is. */
834
- parameter(value: unknown): Sql;
835
- operator(operator: string): string;
836
- columnize(columns: ReadonlyArray<string | Expression>): Sql;
837
- compileSelect(query: Builder$1<unknown>): Sql;
838
- /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
839
- compileComponents(query: Builder$1<unknown>): Sql;
840
- compileOrders(query: Builder$1<unknown>): Sql | undefined;
841
- compileWheres(wheres: readonly Where[], keyword?: 'where' | 'on'): Sql | undefined;
842
- compileWhere(where: Where): Sql;
843
- /**
844
- * whereDate(), whereTime(), whereDay(), whereMonth() and whereYear() per driver, as Laravel 12's grammars: MySQL's
845
- * date()/time()/day()/month()/year(), Postgres' ::date, ::time and extract(), SQLite's strftime() compared as text.
846
- */
847
- compileWhereDate(where: Extract<Where, {
848
- type: 'date';
849
- }>): Sql;
772
+ interface RelatedFactory {
773
+ readonly model: new () => Model;
774
+ create(attributes?: Row): Promise<unknown>;
775
+ createOne(attributes?: Row): Promise<Model>;
776
+ state(state: State): RelatedFactory;
777
+ }
778
+ /**
779
+ * A model's factory() typed as its own factory class (Laravel's `@use HasFactory<UserFactory>`): declare it in the
780
+ * model, `declare static factory: HasFactory<UserFactory>` (with `import type`), and User.factory().unverified()
781
+ * type-checks. The factory is still found at run time by name (database/factories/UserFactory.ts).
782
+ */
783
+ type HasFactory<F> = {
784
+ (): F;
785
+ (count: number, state?: State): F & Many;
786
+ } & (typeof Model)['factory'];
787
+ interface HasRelationship {
788
+ factory: RelatedFactory;
789
+ relationship: string;
790
+ pivot: Row;
791
+ }
792
+ interface ForRelationship {
793
+ parent: RelatedFactory | Model;
794
+ relationship: string;
795
+ }
796
+ /** The for() parents one make()/create()/raw() call has resolved: shared by that call's models, made again by the next. */
797
+ type ResolvedParents = Map<ForRelationship, Model>;
798
+ /** The builder state newInstance() copies and changes. */
799
+ interface FactoryState<M extends Model> {
800
+ countValue: number | undefined;
801
+ states: State[];
802
+ hasRelations: HasRelationship[];
803
+ forRelations: ForRelationship[];
804
+ afterMakingCallbacks: Array<(model: M) => unknown>;
805
+ afterCreatingCallbacks: Array<(model: M) => unknown>;
806
+ }
807
+ /**
808
+ * Laravel's model factories: `class UserFactory extends Factory<User> { model = User; definition() { … } }`,
809
+ * then `await User.factory().count(3).create()`, `UserFactory.new().unverified().make()`.
810
+ * Every builder method returns a new factory, so a base factory can be reused.
811
+ */
812
+ declare abstract class Factory<M extends Model = Model> {
813
+ /** The model class this factory makes. */
814
+ abstract model: new () => M;
815
+ /** The default attributes. Values may be factories (created for their key) or (attributes) => value functions. */
816
+ abstract definition(): Row;
817
+ protected countValue: number | undefined;
818
+ protected states: State[];
819
+ protected hasRelations: HasRelationship[];
820
+ protected forRelations: ForRelationship[];
821
+ protected afterMakingCallbacks: Array<(model: M) => unknown>;
822
+ protected afterCreatingCallbacks: Array<(model: M) => unknown>;
823
+ /** A new factory with the given state (Laravel's Factory::new()). */
824
+ static new<F extends AnyFactory>(this: new () => F, state?: State): F;
825
+ /** Registers factory classes for Model.factory() (discoverFactories() does this for database/factories). */
826
+ static register(...factories: Array<new () => AnyFactory>): void;
827
+ /** The registered factory for a model class. */
828
+ static forModel<M extends Model>(model: new () => M): Factory<M>;
829
+ /** Hook for afterMaking()/afterCreating() registrations; runs in new(). */
830
+ configure(): this;
831
+ /** How many models make()/create() produce; they then return a Collection. */
832
+ count(count: number): this & Many;
833
+ /** Overrides attributes: state({ admin: true }) or state((attributes) => ({ … })). */
834
+ state(state: State): this;
835
+ /** Cycles through states per model: sequence({ role: 'admin' }, { role: 'user' }). */
836
+ sequence(...states: State[]): this;
837
+ /** deleted_at = now, for soft-deleting models. */
838
+ trashed(): this;
839
+ /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */
840
+ has(factory: RelatedFactory, relationship?: string, pivot?: Row): this;
850
841
  /**
851
- * whereLike() per driver, as Laravel 12's grammars: Postgres compares the column as text with ilike (like when
852
- * case-sensitive); MySQL uses like (like binary); SQLite uses like, or glob with the pattern translated.
842
+ * Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). A factory parent is made
843
+ * once per make()/create() call, for all of its models, and again by the next call, so a factory kept in a variable
844
+ * never points at a parent an earlier test rolled back.
853
845
  */
854
- compileWhereLike(where: Extract<Where, {
855
- type: 'like';
856
- }>): Sql;
857
- compileJoin(joinClause: JoinClause): Sql;
858
- compileHavings(havings: readonly Having[]): Sql | undefined;
859
- compileLimitOffset(limit: number | undefined, offset: number | undefined): Sql | undefined;
860
- compileLock(mode: 'update' | 'share' | undefined): Sql | undefined;
861
- /** `select count(*) as aggregate …`. Orders, limit and offset are dropped; grouped or distinct queries are wrapped. */
862
- compileAggregate(query: Builder$1<unknown>, fn: string, column: string | Expression): Sql;
863
- compileExists(query: Builder$1<unknown>): Sql;
864
- compileInsert(query: Builder$1<unknown>, rows: readonly Row[]): Sql;
865
- compileInsertOrIgnore(query: Builder$1<unknown>, rows: readonly Row[]): Sql;
866
- /** `into "table" ("a", "b") values (?, ?), (?, ?)`. Columns are the union of every row's keys; a missing key binds null. */
867
- compileInsertBody(query: Builder$1<unknown>, rows: readonly Row[]): Sql;
868
- compileInsertGetId(query: Builder$1<unknown>, row: Row, keyName: string): Sql;
869
- compileUpsert(query: Builder$1<unknown>, rows: readonly Row[], uniqueBy: readonly string[], update: readonly string[]): Sql;
870
- compileUpdate(query: Builder$1<unknown>, values: Row): Sql;
871
- compileDelete(query: Builder$1<unknown>): Sql;
872
- compileTruncate(query: Builder$1<unknown>): Sql[];
873
- compileRandom(): Expression;
874
- private assertSimpleMutation;
875
- private mysqlOrderAndLimit;
846
+ for(parent: RelatedFactory | Model, relationship?: string): this;
847
+ afterMaking(callback: (model: M) => unknown): this;
848
+ afterCreating(callback: (model: M) => unknown): this;
849
+ /** The attributes only, without a model (a Row, or a Row[] after count()). */
850
+ raw(attributes?: Row): Promise<RawResult<this>>;
851
+ /** Unsaved models (afterMaking callbacks run). */
852
+ make(attributes?: Row): Promise<FactoryResult<this, M>>;
853
+ /** Saved models, with their has() relations (afterCreating callbacks run). */
854
+ create(attributes?: Row): Promise<FactoryResult<this, M>>;
855
+ makeOne(attributes?: Row): Promise<M>;
856
+ createOne(attributes?: Row): Promise<M>;
857
+ /** One model per record (or `count` models), in the model's Eloquent collection. */
858
+ createMany(records: number | Row[]): Promise<EloquentCollection<M>>;
859
+ /** The models in their own Eloquent collection (the model's newCollection()). */
860
+ private collect;
861
+ protected newInstance(changes: Partial<FactoryState<M>>): this;
862
+ protected makeModels(attributes: Row): Promise<M[]>;
863
+ /** definition() + states + overrides + for() parents, with factory and function values expanded. */
864
+ protected attributesFor(overrides: Row, index: number, parents?: ResolvedParents): Promise<Row>;
865
+ private parentAttributes;
866
+ private createChildren;
867
+ private relationOn;
868
+ private result;
876
869
  }
870
+ /** Imports every factory file in a directory and registers its exported Factory classes. */
871
+ declare function discoverFactories(path: string): Promise<void>;
877
872
 
878
- type WhereBoolean = 'and' | 'or';
879
- type Direction = 'asc' | 'desc';
880
- type ColumnRef = string | Expression;
881
- type Where = {
882
- type: 'basic';
883
- column: ColumnRef | Builder$1<unknown>;
884
- operator: string;
885
- value: unknown;
886
- boolean: WhereBoolean;
887
- } | {
888
- type: 'in';
889
- column: ColumnRef;
890
- values: readonly unknown[] | Builder$1<unknown>;
891
- not: boolean;
892
- boolean: WhereBoolean;
893
- } | {
894
- type: 'null';
895
- column: ColumnRef;
896
- not: boolean;
897
- boolean: WhereBoolean;
898
- } | {
899
- type: 'between';
900
- column: ColumnRef;
901
- values: readonly [unknown, unknown];
902
- not: boolean;
903
- boolean: WhereBoolean;
904
- } | {
905
- type: 'like';
906
- column: ColumnRef;
907
- value: string;
908
- caseSensitive: boolean;
909
- not: boolean;
910
- boolean: WhereBoolean;
911
- } | {
912
- type: 'column';
913
- first: ColumnRef;
914
- operator: string;
915
- second: ColumnRef;
916
- boolean: WhereBoolean;
917
- } | {
918
- type: 'nested';
919
- query: Builder$1<unknown>;
920
- not: boolean;
921
- boolean: WhereBoolean;
922
- } | {
923
- type: 'exists';
924
- query: Builder$1<unknown>;
925
- not: boolean;
926
- boolean: WhereBoolean;
927
- } | {
928
- type: 'raw';
929
- sql: string;
930
- bindings: readonly unknown[];
931
- boolean: WhereBoolean;
932
- } | {
933
- type: 'date';
934
- part: DatePart;
935
- column: ColumnRef;
936
- operator: string;
937
- value: unknown;
938
- boolean: WhereBoolean;
873
+ /** Laravel's model events. The -ing events of save, delete and restore can cancel by returning false. */
874
+ declare const MODEL_EVENTS: readonly ["retrieved", "creating", "created", "updating", "updated", "saving", "saved", "deleting", "deleted", "restoring", "restored", "forceDeleting", "forceDeleted"];
875
+ type ModelEvent = (typeof MODEL_EVENTS)[number];
876
+ /** A listener receives the model. Returning false from a halting event cancels the operation. */
877
+ type ModelListener<M> = (model: M) => unknown;
878
+ /** 'eloquent.created: Post' (Laravel uses the fully qualified class name; Oriel uses the class name). */
879
+ declare function modelEventName(event: string, className: string): string;
880
+
881
+ declare abstract class Relation<R extends Model = Model, P extends Model = Model, Result = unknown> extends Builder$1<R> {
882
+ readonly parent: P;
883
+ /** The name the relation is loaded under (set when resolved by name, for eager loading and associate()). */
884
+ relationName: string | undefined;
885
+ /** Laravel's Relation::morphMap(): { post: Post } stores 'post' instead of 'Post' in *_type columns. */
886
+ static morphMap(map?: Record<string, typeof Model>, merge?: boolean): Record<string, typeof Model>;
887
+ static getMorphedModel(alias: string): typeof Model | undefined;
888
+ protected constructor(related: R, parent: P);
889
+ getParent(): P;
890
+ getRelated(): R;
891
+ /**
892
+ * When the related table is the parent's own (a category's children, a user's followers), the existence query reads it
893
+ * under an alias, `oriel_reserved_<n>`, so its columns aren't the outer row's. The related model takes the alias as its
894
+ * table, so its qualified columns (keys, soft deletes, a constraint's qualifyColumn()) follow. Returns the alias, or
895
+ * undefined when the tables differ.
896
+ */
897
+ protected aliasSelfTable(query: Builder$1<R>): string | undefined;
898
+ /** A new `oriel_reserved_<n>` alias, for a table a query reads twice. */
899
+ protected static reserveAlias(): string;
900
+ /**
901
+ * @internal After an eager load's constraint: a limit() or offset() set there applies to each parent, as in Laravel 11,
902
+ * on the relations that know the column holding the parent's key.
903
+ */
904
+ limitEagerPerParent(): void;
905
+ /** The column of the eager query holding each row's parent key; undefined where a per-parent limit makes no sense. */
906
+ protected eagerPartitionColumn(): string | undefined;
907
+ /** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */
908
+ protected init(): void;
909
+ /** The constraints for one parent: where comments.post_id = post.id. */
910
+ abstract addConstraints(): void;
911
+ /** The constraints for many parents: where comments.post_id in (…). */
912
+ abstract addEagerConstraints(models: P[]): void;
913
+ /** Sets the empty value (null or an empty collection) on every parent. */
914
+ abstract initRelation(models: P[], relation: string): P[];
915
+ /** Distributes the eagerly loaded results to their parents. */
916
+ abstract match(models: P[], results: R[], relation: string): P[];
917
+ /** The relation's value for this parent (a model, null or a collection). */
918
+ abstract getResults(): Promise<Result>;
919
+ /** The query of has()/whereHas(): related rows that belong to the outer query's current row. */
920
+ abstract getRelationExistenceQuery(query: Builder$1<R>, parentQuery: Builder$1<P>, columns?: ColumnRef[]): Builder$1<R>;
921
+ /** Runs the eager query. */
922
+ getEager(): Promise<Collection<R>>;
923
+ /** select count(*) … for withCount() and has('comments', '>=', 3). */
924
+ getRelationExistenceCountQuery(query: Builder$1<R>, parentQuery: Builder$1<P>): Builder$1<R>;
925
+ /** The distinct non-null values of `key` on the models (the eager whereIn list). */
926
+ protected keysOf(models: Model[], key: string): unknown[];
927
+ }
928
+
929
+ /** post.author(): this model (the child) holds the related model's key. */
930
+ declare class BelongsTo<R extends Model, P extends Model = Model> extends Relation<R, P, R | null> {
931
+ readonly foreignKey: string;
932
+ readonly ownerKey: string;
933
+ /**
934
+ * @param foreignKey the column on the child ('user_id')
935
+ * @param ownerKey the key on the related model it points at ('id')
936
+ */
937
+ constructor(related: R, child: P, foreignKey: string, ownerKey: string, relationName?: string);
938
+ getChild(): P;
939
+ getForeignKeyName(): string;
940
+ getQualifiedForeignKeyName(): string;
941
+ getOwnerKeyName(): string;
942
+ getQualifiedOwnerKeyName(): string;
943
+ addConstraints(): void;
944
+ addEagerConstraints(models: P[]): void;
945
+ getResults(): Promise<R | null>;
946
+ initRelation(models: P[], relation: string): P[];
947
+ match(models: P[], results: R[], relation: string): P[];
948
+ /** Points the child at `model` (sets the foreign key and the loaded relation). Save the child afterwards. */
949
+ associate(model: R | null): P;
950
+ /** Clears the foreign key. Save the child afterwards. */
951
+ dissociate(): P;
952
+ getRelationExistenceQuery(query: Builder$1<R>, _parentQuery: Builder$1<P>, columns?: ColumnRef[]): Builder$1<R>;
953
+ /** The loaded-relation name: the resolved name, else the related class in camelCase (author → pass it explicitly). */
954
+ private relationKey;
955
+ }
956
+
957
+ /** A model key of a known type: find() with one gives a model (or undefined), never a collection. */
958
+ type ModelKey = string | number | bigint;
959
+ /**
960
+ * A model's attribute types. `oriel model:types` adds a phantom `$attributes?: { … }` member to each model through
961
+ * declaration merging; without it every attribute is `unknown`.
962
+ */
963
+ type Attributes<M> = M extends {
964
+ $attributes?: infer A;
965
+ } ? (unknown extends A ? Row : NonNullable<A>) : Row;
966
+ /**
967
+ * The column names a builder of M accepts: the generated attribute names plus any qualified `table.column`.
968
+ * Without generated types, any string.
969
+ */
970
+ type Column<M> = M extends {
971
+ $attributes?: infer A;
972
+ } ? unknown extends A ? string : (keyof NonNullable<A> & string) | `${string}.${string}` : string;
973
+ /** A model class: constructible with no arguments, with Model's statics. */
974
+ type ModelClass<M extends Model = Model> = (new () => M) & Omit<typeof Model, 'prototype'>;
975
+ type AnyScope = (query: any, ...args: any[]) => unknown;
976
+ /** 'scopePublished' → 'published'. */
977
+ type ScopeName<K> = K extends `scope${infer Name}` ? Uncapitalize<Name> : never;
978
+ /**
979
+ * The local scopes of a model class as builder methods: static scopeOfType(q, type) → query.ofType(type). `M` is the
980
+ * model type the builder gives (with what with() loads), kept through each scope; `$modelClass` lets with() find C.
981
+ */
982
+ type Scopes<C extends typeof Model, M extends Model = InstanceType<C>> = {
983
+ [K in keyof C as ScopeName<K>]: C[K] extends (query: never, ...args: infer A) => unknown ? (...args: A) => ModelBuilder<C, M> : never;
984
+ } & {
985
+ readonly $modelClass?: C;
939
986
  };
940
- /** The part of a date or time column a date where clause compares (whereDate() → 'date', whereYear() → 'year', …). */
941
- type DatePart = 'date' | 'time' | 'day' | 'month' | 'year';
942
- /** What a date where clause compares with: a Date (read in UTC), a string, a number, or DB.raw(). */
943
- type DateWhereValue = Date | string | number | Expression;
944
- /** whereDate('published_at', '2026-01-05') or whereDate('published_at', '>=', new Date()). */
945
- type DateWhereArgs = [value: DateWhereValue] | [operator: string, value: DateWhereValue];
946
- type Having = {
947
- column: ColumnRef;
948
- operator: string;
949
- value: unknown;
950
- boolean: WhereBoolean;
951
- } | {
952
- raw: Expression;
953
- boolean: WhereBoolean;
987
+ /** Post.query(): the Eloquent builder of Post (or of `M`, Post with what with() loads), plus Post's local scopes. */
988
+ type ModelBuilder<C extends typeof Model, M extends Model = InstanceType<C>> = Builder$1<M> & Scopes<C, M>;
989
+ /** The static scope proxy type used by generated types: Post.published(). */
990
+ type ScopeStatic<C extends typeof Model, K extends keyof C> = C[K] extends AnyScope ? C[K] extends (query: never, ...args: infer A) => unknown ? (...args: A) => ModelBuilder<C> : never : never;
991
+ /** The arguments where() accepts on a builder of M (column names are checked when types are generated). */
992
+ type WhereArgs<M, Q> = [column: Column<M> | Expression, value: unknown] | [column: Column<M> | Expression, operator: Operator | string, value: unknown] | [conditions: Row] | [callback: (query: Q) => unknown];
993
+ /** A model's own members: Model's are left out (none is a relation or a mutator, and reading them would loop). */
994
+ type OwnKeys<M> = Exclude<keyof M, keyof Model>;
995
+ /** The names of a model's relation methods (methods returning a relation). */
996
+ type RelationNames<M> = {
997
+ [K in OwnKeys<M>]: M[K] extends () => {
998
+ getResults(): Promise<any>;
999
+ } ? K : never;
1000
+ }[OwnKeys<M>] & string;
1001
+ /** The loaded value of a relation: what its getResults() resolves to (a model or null, or a Collection). */
1002
+ type RelationValue<M, K extends keyof M> = M[K] extends () => {
1003
+ getResults(): Promise<infer T>;
1004
+ } ? T : never;
1005
+ /**
1006
+ * A model whose type has no generated attributes, or that is a type parameter (`this` inside its own methods, a helper's
1007
+ * `M extends Model`): its writes and loads take any attributes and relations, as before typed writes. The checked
1008
+ * signatures come first; overloads whose `this` is one of these take what they can't decide.
1009
+ */
1010
+ type UntypedModel = Model & {
1011
+ readonly $attributes?: undefined;
954
1012
  };
955
- type Order = {
956
- column: ColumnRef;
957
- direction: Direction;
958
- } | {
959
- raw: Expression;
1013
+ /** Whether `oriel model:types` generated M's attributes: only then are its writes checked. */
1014
+ type HasGeneratedTypes<M> = M extends {
1015
+ $attributes?: infer A;
1016
+ } ? (unknown extends A ? false : true) : false;
1017
+ /**
1018
+ * What a write takes for an attribute typed T: T, nothing, an expression written as SQL (`raw('votes + 1')`), or what
1019
+ * Oriel turns into T when it saves (a date's text or timestamp, a number's text, a string's number or date, 0/1 for a
1020
+ * boolean).
1021
+ */
1022
+ type WriteValue<T> = T | undefined | Expression | (Date extends T ? string | number : never) | (number extends T ? string | bigint : never) | (string extends T ? number | bigint | Date : never) | (boolean extends T ? 0 | 1 | '0' | '1' : never);
1023
+ /** 'FirstName' → 'first_name'. */
1024
+ type SnakeCase<S extends string> = S extends `${infer Head}${infer Rest}` ? `${Head extends Lowercase<Head> ? Head : `_${Lowercase<Head>}`}${SnakeCase<Rest>}` : S;
1025
+ /** 'setFirstNameAttribute' → 'first_name'. */
1026
+ type MutatorKey<K> = K extends `set${infer Name}Attribute` ? SnakeCase<Uncapitalize<Name>> : never;
1027
+ /** A model's public set mutators, by the attribute name they set, each with the value it takes. */
1028
+ type Setters<M> = {
1029
+ [S in OwnKeys<M> & string as M[S] extends (...args: never[]) => unknown ? MutatorKey<S> : never]: M[S] extends (value: infer V, ...args: never[]) => unknown ? V : unknown;
960
1030
  };
961
- /** A column, an expression, or `(subquery) as alias` (`exists (subquery) as alias` with exists). */
962
- type SelectColumn = ColumnRef | {
963
- query: Builder$1<unknown>;
964
- as: string;
965
- exists?: boolean;
1031
+ /** The keys a write of M takes: its attribute names, and the snake_case names of its public `set<Name>Attribute()`. */
1032
+ type WritableKey<M> = (keyof Attributes<M> & string) | (keyof Setters<M> & string);
1033
+ /** The type a write gives a key: the attribute's, or what its set mutator takes. */
1034
+ type WriteType<M, K> = K extends keyof Attributes<M> ? Attributes<M>[K] : K extends keyof Setters<M> ? Setters<M>[K] : never;
1035
+ /**
1036
+ * What a write of M (create(), fill(), update(), …) takes for the attributes T: any `Row` when M has no generated
1037
+ * types, or when T has an index signature (keys known only at run time); else each key a `WritableKey<M>` and each
1038
+ * value its `WriteValue`, unless it is typed `unknown` (a validated field with no type rule). Every write is partial.
1039
+ */
1040
+ type WriteAttributes<M, T = Row> = string extends keyof T ? Row : HasGeneratedTypes<M> extends true ? {
1041
+ [K in keyof T]: K extends WritableKey<M> ? WriteCheck<T[K], WriteValue<WriteType<M, K>>> : never;
1042
+ } : Row;
1043
+ /**
1044
+ * A value that fits is kept as it is (an enum member stays one: intersected with its literal it would be `never`), an
1045
+ * `unknown` one too; any other value is held to what fits.
1046
+ */
1047
+ type WriteCheck<V, Fits> = unknown extends V ? V : V extends Fits ? V : Fits;
1048
+ /** The model a relation method reaches. */
1049
+ type RelatedOf<M, K> = K extends keyof M ? (M[K] extends () => {
1050
+ getRelated(): infer R;
1051
+ } ? R : never) : never;
1052
+ type Shallower = [never, 0, 1, 2];
1053
+ /**
1054
+ * A model's relation paths, `'comments'` or `'comments.article'`: each segment a relation of the model before it, three
1055
+ * deep. Deeper, or below a model without generated types, any string; a model without them takes any string.
1056
+ */
1057
+ type RelationPath<M, Depth extends number = 3> = [Depth] extends [never] ? string : HasGeneratedTypes<M> extends true ? {
1058
+ [K in RelationNames<M>]: K | `${K}.${RelationPath<RelatedOf<M, K>, Shallower[Depth]>}`;
1059
+ }[RelationNames<M>] : string;
1060
+ /** A name with()/load() take: a relation path, optionally with its columns (`'comments:id,body'`). */
1061
+ type EagerLoadName<M> = HasGeneratedTypes<M> extends true ? RelationPath<M> | `${RelationPath<M>}:${string}` : string;
1062
+ /** A name withCount() and the other aggregates take: a relation, optionally aliased (`'comments as approved_count'`). */
1063
+ type AggregateName<M> = HasGeneratedTypes<M> extends true ? RelationNames<M> | `${RelationNames<M>} as ${string}` : string;
1064
+ /** with('author'), with(['author', 'comments.user']), with({ comments: (q) => q.latest() }), with('author:id,name'). */
1065
+ type EagerLoadSpec<M = Model> = EagerLoadName<M> | readonly EagerLoadName<M>[] | {
1066
+ readonly [K in EagerLoadName<M>]?: RelationConstraint;
966
1067
  };
967
- type NestedCallback<Q> = (query: Q) => unknown;
968
- /** The value when()'s callback receives: the condition's type without its falsy members. */
969
- type Truthy<V> = Exclude<V, false | 0 | 0n | '' | null | undefined>;
970
- /** The key a selected column comes back under: 'users.name' → 'name', 'name as n' → 'n'. */
971
- declare function columnKey(column: string): string;
1068
+ /** @internal What the methods taking eager-load specs read at run time. */
1069
+ type LooseSpec = string | readonly string[] | Readonly<Record<string, RelationConstraint | undefined>>;
1070
+ /** A name checked against the allowed ones: kept when it is one, or when it is typed `string`; else the allowed ones. */
1071
+ type CheckName<N, Allowed> = string extends N ? N : N extends Allowed ? N : Allowed;
1072
+ /** One spec checked against the names a method allows: a name, a list of names, or an object keyed by them. */
1073
+ type CheckSpec<S, Allowed> = S extends string ? CheckName<S, Allowed> : S extends readonly unknown[] ? {
1074
+ [I in keyof S]: CheckName<S[I], Allowed>;
1075
+ } : {
1076
+ [K in keyof S]: K extends string ? (string extends K ? S[K] : K extends Allowed ? S[K] : never) : S[K];
1077
+ };
1078
+ /** @internal with()/load()'s specs, checked: each name one of M's relation paths. The literals stay readable from S. */
1079
+ type EagerLoads<M, S extends readonly unknown[]> = S & {
1080
+ [I in keyof S]: CheckSpec<S[I], EagerLoadName<M>>;
1081
+ };
1082
+ /** @internal withCount()'s and the aggregates' specs, checked: each name one of M's relations, maybe aliased. */
1083
+ type Aggregates<M, S extends readonly unknown[]> = S & {
1084
+ [I in keyof S]: CheckSpec<S[I], AggregateName<M>>;
1085
+ };
1086
+ /** @internal withSum() and its kin: one spec or a list of them, checked. */
1087
+ type AggregateSpecs<M, S> = S & (S extends readonly unknown[] ? {
1088
+ [I in keyof S]: CheckSpec<S[I], AggregateName<M>>;
1089
+ } : CheckSpec<S, AggregateName<M>>);
1090
+ /** @internal has(), whereHas() and their kin: a relation path of M. */
1091
+ type RelationPathArg<M, N extends string> = N & CheckName<N, RelationPath<M>>;
1092
+ /** 'id, name' → 'id' | 'name'. */
1093
+ type Trim<S extends string> = S extends ` ${infer R}` ? Trim<R> : S extends `${infer R} ` ? Trim<R> : S;
1094
+ type SplitColumns<S extends string> = S extends `${infer Head},${infer Rest}` ? Trim<Head> | SplitColumns<Rest> : Trim<S>;
1095
+ /** A relation in a LoadedTree with nothing loaded below it (`{}`). */
1096
+ type LoadedLeaf = Record<never, never>;
1097
+ /** One eager-load name as a tree: 'comments.author' → { comments: { author: {} } }, 'tags:id,name' → { tags: { $columns: … } }. */
1098
+ type PathTree<P extends string> = P extends `${infer Head}.${infer Rest}` ? {
1099
+ [K in Head]: PathTree<Rest>;
1100
+ } : P extends `${infer Name}:${infer Columns}` ? {
1101
+ [K in Name]: {
1102
+ $columns: SplitColumns<Columns>;
1103
+ };
1104
+ } : {
1105
+ [K in P]: LoadedLeaf;
1106
+ };
1107
+ /** The names in with()'s or load()'s specs: a name, a list's names, an object's keys. */
1108
+ type SpecNames<S> = S extends string ? S : S extends readonly (infer E)[] ? Extract<E, string> : S extends object ? Extract<keyof S, string> : never;
1109
+ type UnionToIntersection<U> = (U extends unknown ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
1110
+ type DeepSimplify<T> = T extends object ? {
1111
+ [K in keyof T]: DeepSimplify<T[K]>;
1112
+ } : T;
972
1113
  /**
973
- * Laravel's query builder: DB.table('users').where('votes', '>', 100).get().
974
- * Implements the QueryBuilder contract other components use (Queue, Cache, Session, Validation).
1114
+ * What with() or load() loads, as a tree: with('user', 'comments.author', 'tags:id,name', { comments: … }) →
1115
+ * `{ user: {}; comments: { author: {} }; tags: { $columns: 'id' | 'name' } }`. A name typed `string` records nothing.
975
1116
  */
976
- declare class Builder$1<T = Row> implements QueryBuilder<T> {
977
- readonly connection: Connection;
978
- readonly grammar: Grammar;
979
- columns: SelectColumn[];
980
- distinctRows: boolean;
981
- fromTable: string | Expression | undefined;
982
- joins: JoinClause[];
983
- wheres: Where[];
984
- groups: ColumnRef[];
985
- havings: Having[];
986
- orders: Order[];
987
- limitValue: number | undefined;
988
- offsetValue: number | undefined;
989
- lockMode: 'update' | 'share' | undefined;
990
- constructor(connection: Connection, table?: string | Expression);
991
- from(table: string | Expression): this;
992
- select(...columns: Array<ColumnRef | ColumnRef[]>): this;
993
- addSelect(...columns: Array<ColumnRef | ColumnRef[]>): this;
994
- selectRaw(expression: string, bindings?: readonly unknown[]): this;
995
- /** Adds `(subquery) as alias` to the select list. */
996
- selectSub(query: Builder$1<unknown>, as: string): this;
997
- distinct(): this;
998
- where(column: ColumnRef, value: unknown): this;
999
- where(column: ColumnRef, operator: Operator | string, value: unknown): this;
1000
- where(conditions: Row): this;
1001
- where(callback: NestedCallback<Builder$1<T>>): this;
1002
- orWhere(column: ColumnRef, value: unknown): this;
1003
- orWhere(column: ColumnRef, operator: Operator | string, value: unknown): this;
1004
- orWhere(conditions: Row): this;
1005
- orWhere(callback: NestedCallback<Builder$1<T>>): this;
1006
- /** where not (…): whereNot(q => q.where('a', 1).orWhere('b', 2)). */
1007
- whereNot(callback: NestedCallback<Builder$1<T>>): this;
1008
- orWhereNot(callback: NestedCallback<Builder$1<T>>): this;
1009
- whereIn(column: ColumnRef, values: readonly unknown[] | Builder$1<unknown>): this;
1010
- orWhereIn(column: ColumnRef, values: readonly unknown[] | Builder$1<unknown>): this;
1011
- whereNotIn(column: ColumnRef, values: readonly unknown[] | Builder$1<unknown>): this;
1012
- orWhereNotIn(column: ColumnRef, values: readonly unknown[] | Builder$1<unknown>): this;
1013
- whereNull(columns: ColumnRef | ColumnRef[]): this;
1014
- orWhereNull(column: ColumnRef): this;
1015
- whereNotNull(columns: ColumnRef | ColumnRef[]): this;
1016
- orWhereNotNull(column: ColumnRef): this;
1017
- whereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
1018
- orWhereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
1019
- whereNotBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
1020
- /** Compares the date part of a column: whereDate('published_at', '2026-01-05'), whereDate('published_at', '<', new Date()). */
1021
- whereDate(column: ColumnRef, ...args: DateWhereArgs): this;
1022
- orWhereDate(column: ColumnRef, ...args: DateWhereArgs): this;
1023
- /** Compares the time of day: whereTime('published_at', '>=', '09:00:00'). */
1024
- whereTime(column: ColumnRef, ...args: DateWhereArgs): this;
1025
- orWhereTime(column: ColumnRef, ...args: DateWhereArgs): this;
1026
- /** Compares the day of the month: whereDay('published_at', 5). */
1027
- whereDay(column: ColumnRef, ...args: DateWhereArgs): this;
1028
- orWhereDay(column: ColumnRef, ...args: DateWhereArgs): this;
1029
- /** Compares the month: whereMonth('published_at', 12). */
1030
- whereMonth(column: ColumnRef, ...args: DateWhereArgs): this;
1031
- orWhereMonth(column: ColumnRef, ...args: DateWhereArgs): this;
1032
- /** Compares the year: whereYear('published_at', '>=', 2026). */
1033
- whereYear(column: ColumnRef, ...args: DateWhereArgs): this;
1034
- orWhereYear(column: ColumnRef, ...args: DateWhereArgs): this;
1117
+ type LoadedTree<Specs extends readonly unknown[]> = string extends SpecNames<Specs[number]> ? LoadedLeaf : [SpecNames<Specs[number]>] extends [never] ? LoadedLeaf : DeepSimplify<UnionToIntersection<PathTree<SpecNames<Specs[number]>>>>;
1118
+ /** A model with what was loaded on it, in the phantom `$loaded` (page prop types read it). Nothing loaded: the model. */
1119
+ type WithLoaded<M, Tree> = keyof Tree extends never ? M : M & {
1120
+ readonly $loaded?: Tree;
1121
+ };
1122
+ /** @internal with()'s builder: the query's builder over the loaded model type (with its scopes), then the builder itself. */
1123
+ type LoadedBuilder<Self, M2 extends Model> = (Self extends {
1124
+ readonly $modelClass?: infer C;
1125
+ } ? C extends typeof Model ? ModelBuilder<C, M2> : Builder$1<M2> : Builder$1<M2>) & Self;
1126
+
1127
+ /** attach()/sync() accept ids, models, or { id: pivotAttributes }. */
1128
+ type PivotIds = unknown | readonly unknown[] | Record<string, Row>;
1129
+ interface SyncChanges {
1130
+ attached: unknown[];
1131
+ detached: unknown[];
1132
+ updated: unknown[];
1133
+ }
1134
+ /**
1135
+ * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).
1136
+ * Each related model carries its pivot row as `tag.pivot` (withPivot() adds columns, withTimestamps() the timestamps).
1137
+ */
1138
+ declare class BelongsToMany<R extends Model, P extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {
1139
+ readonly table: string;
1140
+ readonly foreignPivotKey: string;
1141
+ readonly relatedPivotKey: string;
1142
+ readonly parentKey: string;
1143
+ readonly relatedKey: string;
1144
+ protected pivotColumns: string[];
1145
+ protected pivotTimestamps: [string, string] | undefined;
1146
+ constructor(related: R, parent: P, table: string, foreignPivotKey: string, relatedPivotKey: string, parentKey: string, relatedKey: string);
1147
+ qualifyPivotColumn(column: string): string;
1148
+ getTable(): string;
1149
+ getForeignPivotKeyName(): string;
1150
+ getRelatedPivotKeyName(): string;
1151
+ getParentKey(): unknown;
1152
+ addConstraints(): void;
1153
+ addEagerConstraints(models: P[]): void;
1154
+ /** Extra pivot columns to load onto tag.pivot. */
1155
+ withPivot(...columns: Array<string | string[]>): this;
1156
+ /** The pivot table has created_at/updated_at: they are set on attach() and loaded onto tag.pivot. */
1157
+ withTimestamps(createdAt?: string, updatedAt?: string): this;
1158
+ wherePivot(column: string, operator: unknown, value?: unknown): this;
1159
+ wherePivotIn(column: string, values: readonly unknown[]): this;
1160
+ /** Selects the related columns plus the pivot columns (as pivot_*), then moves those onto each model's pivot. */
1161
+ runSelect(): Promise<R[]>;
1162
+ getResults(): Promise<EloquentCollection<R>>;
1163
+ initRelation(models: P[], relation: string): P[];
1164
+ match(models: P[], results: R[], relation: string): P[];
1165
+ protected eagerPartitionColumn(): string;
1166
+ getRelationExistenceQuery(query: Builder$1<R>, _parentQuery: Builder$1<P>, columns?: ColumnRef[]): Builder$1<R>;
1167
+ /** Inserts pivot rows for ids (or models, or { id: attributes }), with shared extra attributes. */
1168
+ attach(ids: PivotIds, attributes?: Row): Promise<void>;
1169
+ /** Deletes pivot rows for ids, or every pivot row of the parent. Returns how many were deleted. */
1170
+ detach(ids?: PivotIds): Promise<number>;
1171
+ /** Makes the pivot rows exactly ids: attaches the missing ones, detaches the others, updates given attributes. */
1172
+ sync(ids: PivotIds, detaching?: boolean): Promise<SyncChanges>;
1173
+ syncWithoutDetaching(ids: PivotIds): Promise<SyncChanges>;
1174
+ /** Attaches the ids that aren't attached and detaches the ones that are. */
1175
+ toggle(ids: PivotIds): Promise<{
1176
+ attached: unknown[];
1177
+ detached: unknown[];
1178
+ }>;
1179
+ /** Updates the pivot row of one related id. Returns the number of affected rows. */
1180
+ updateExistingPivot(id: unknown, attributes: Row): Promise<number>;
1181
+ /** Saves a new related model and attaches it. */
1182
+ create<const T extends object = Row>(attributes?: T & WriteAttributes<R, T>, pivotAttributes?: Row): Promise<R>;
1183
+ create(this: BelongsToMany<UntypedModel, P>, attributes?: Row, pivotAttributes?: Row): Promise<R>;
1184
+ /** Saves a related model and attaches it. */
1185
+ save(model: R, pivotAttributes?: Row): Promise<R>;
1186
+ /** A plain query builder on the pivot table. */
1187
+ newPivotQuery(): Builder<Row>;
1188
+ private currentPivotIds;
1189
+ private pivotSelectColumns;
1190
+ private hydratePivot;
1191
+ private pivotRow;
1192
+ /** ids → Map(id → extra pivot attributes). Models become their related key. */
1193
+ private parseIds;
1194
+ private idOf;
1195
+ private isModel;
1196
+ /** Object keys are strings; numeric ones go back to numbers for integer keys. */
1197
+ private castKey;
1198
+ }
1199
+
1200
+ /** For morphOne/morphMany: the qualified type column and the parent's morph class stored in it. */
1201
+ interface MorphConstraint {
1202
+ type: string;
1203
+ value: string;
1204
+ }
1205
+ /**
1206
+ * The shared half of hasOne, hasMany, morphOne and morphMany: the related table holds the foreign key (and, for
1207
+ * the morph relations, the parent's type).
1208
+ */
1209
+ declare abstract class HasOneOrMany<R extends Model, P extends Model, Result> extends Relation<R, P, Result> {
1210
+ readonly foreignKey: string;
1211
+ readonly localKey: string;
1212
+ readonly morph?: MorphConstraint | undefined;
1213
+ /** The relation on each related model that chaperone() points back at the parent. */
1214
+ protected inverseRelationship: string | undefined;
1035
1215
  /**
1036
- * Laravel's whereLike(): the value is the pattern, `%` and `_` included (`whereLike('title', `%${term}%`)`).
1037
- * Case-insensitive unless caseSensitive: ilike on Postgres, like on MySQL and SQLite (their like already ignores
1038
- * case: MySQL through the column's collation, SQLite for ASCII letters). Case-sensitive is like on Postgres,
1039
- * like binary on MySQL and glob on SQLite.
1216
+ * @param foreignKey the qualified foreign key on the related table ('comments.post_id')
1217
+ * @param localKey the key on the parent it points at ('id')
1218
+ * @param morph the type column and value, for morphOne/morphMany
1040
1219
  */
1041
- whereLike(column: ColumnRef, value: string, caseSensitive?: boolean, boolean?: WhereBoolean, not?: boolean): this;
1042
- orWhereLike(column: ColumnRef, value: string, caseSensitive?: boolean): this;
1043
- whereNotLike(column: ColumnRef, value: string, caseSensitive?: boolean, boolean?: WhereBoolean): this;
1044
- orWhereNotLike(column: ColumnRef, value: string, caseSensitive?: boolean): this;
1045
- /** Compares two columns: whereColumn('updated_at', '>', 'created_at'). */
1046
- whereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef, boolean?: WhereBoolean): this;
1047
- orWhereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef): this;
1048
- whereRaw(sql: string, bindings?: readonly unknown[], boolean?: WhereBoolean): this;
1049
- orWhereRaw(sql: string, bindings?: readonly unknown[]): this;
1050
- whereExists(query: Builder$1<unknown> | NestedCallback<Builder$1<Row>>, boolean?: WhereBoolean, not?: boolean): this;
1051
- orWhereExists(query: Builder$1<unknown> | NestedCallback<Builder$1<Row>>): this;
1052
- whereNotExists(query: Builder$1<unknown> | NestedCallback<Builder$1<Row>>): this;
1053
- /** `(select …) <operator> value`: used by has('comments', '>=', 3). */
1054
- whereSub(query: Builder$1<unknown>, operator: string, value: unknown, boolean?: WhereBoolean): this;
1055
- /** Appends another builder's where clauses as one nested group. */
1056
- addNestedWhereQuery(query: Builder$1<unknown>, boolean?: WhereBoolean, not?: boolean): this;
1057
- join(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef, type?: JoinType): this;
1058
- leftJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this;
1059
- rightJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this;
1060
- crossJoin(table: string | Expression): this;
1061
- groupBy(...columns: ColumnRef[]): this;
1062
- having(column: ColumnRef, operatorOrValue: unknown, value?: unknown, boolean?: WhereBoolean): this;
1063
- havingRaw(sql: string, bindings?: readonly unknown[], boolean?: WhereBoolean): this;
1064
- orderBy(column: ColumnRef, direction?: Direction | Uppercase<Direction>): this;
1065
- orderByDesc(column: ColumnRef): this;
1066
- latest(column?: ColumnRef): this;
1067
- oldest(column?: ColumnRef): this;
1068
- inRandomOrder(): this;
1069
- orderByRaw(sql: string, bindings?: readonly unknown[]): this;
1070
- /** Removes existing orders, optionally adding a new one. */
1071
- reorder(column?: ColumnRef, direction?: Direction): this;
1072
- limit(count: number): this;
1073
- take(count: number): this;
1074
- offset(count: number): this;
1075
- skip(count: number): this;
1076
- forPage(page: number, perPage?: number): this;
1077
- lockForUpdate(): this;
1078
- sharedLock(): this;
1220
+ constructor(related: R, parent: P, foreignKey: string, localKey: string, morph?: MorphConstraint | undefined);
1221
+ /** 'post_id' */
1222
+ getForeignKeyName(): string;
1223
+ getQualifiedForeignKeyName(): string;
1224
+ getParentKey(): unknown;
1225
+ getQualifiedParentKeyName(): string;
1226
+ /** 'commentable_type' for a morph relation. */
1227
+ getMorphType(): string | undefined;
1228
+ /** The parent's value in the type column, for a morph relation. */
1229
+ getMorphClass(): string | undefined;
1079
1230
  /**
1080
- * Laravel's when(): callback(query, value) runs when the value is truthy, otherwise(query, value) when it is falsy.
1081
- * A function value is called with the query first and its result is the value. Truthiness is JavaScript's, so `'0'`
1082
- * and `[]` are truthy: a `?active=0` filter applies, where Laravel would skip it. Returns the query; what the
1083
- * callbacks return is ignored.
1084
- *
1085
- * @example
1086
- * Post.query().when(request.query('q'), (query, q) => query.whereLike('title', `%${q}%`))
1231
+ * Laravel's chaperone(): every related model this relation loads, eagerly or lazily, or makes, gets the parent as
1232
+ * its `relation` (guessed when not given: post_id → post, the parent's class, owner), so reading it needs no query:
1233
+ * `comments() { return this.hasMany(Comment).chaperone() }`.
1087
1234
  */
1088
- when<V>(value: (query: this) => V, callback: (query: this, value: Truthy<V>) => unknown, otherwise?: (query: this, value: V) => unknown): this;
1089
- when<V>(value: V, callback: (query: this, value: Truthy<V>) => unknown, otherwise?: (query: this, value: V) => unknown): this;
1090
- /** Laravel's unless(): when() with the condition reversed. callback(query, value) runs when the value is falsy. */
1091
- unless<V>(value: (query: this) => V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: Truthy<V>) => unknown): this;
1092
- unless<V>(value: V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: Truthy<V>) => unknown): this;
1093
- tap(callback: (query: this) => unknown): this;
1094
- get(): Promise<Collection<T>>;
1095
- /** The collection get() and chunk() hand out (Eloquent's builder makes the model's collection). */
1096
- protected newCollection(items: T[]): Collection<T>;
1097
- /** The raw rows, without a Collection around them. */
1098
- runSelect(): Promise<T[]>;
1099
- first(): Promise<T | undefined>;
1100
- find(id: unknown, keyName?: string): Promise<T | undefined>;
1101
- value<V = unknown>(column: string): Promise<V | undefined>;
1102
- pluck<V = unknown>(column: string): Promise<Collection<V>>;
1103
- count(column?: ColumnRef): Promise<number>;
1104
- min<V = unknown>(column: ColumnRef): Promise<V | undefined>;
1105
- max<V = unknown>(column: ColumnRef): Promise<V | undefined>;
1106
- sum(column: ColumnRef): Promise<number>;
1107
- avg(column: ColumnRef): Promise<number | undefined>;
1108
- aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown>;
1109
- exists(): Promise<boolean>;
1110
- doesntExist(): Promise<boolean>;
1111
- insert(values: Row | Row[]): Promise<void>;
1112
- /** Inserts one row and returns its auto-increment id. */
1113
- insertGetId(values: Row, keyName?: string): Promise<number | string>;
1114
- /** Inserts rows, skipping the ones that violate a unique constraint. Returns how many were inserted. */
1115
- insertOrIgnore(values: Row | Row[]): Promise<number>;
1116
- update(values: Row): Promise<number>;
1117
- /** Updates the row matching attributes, or inserts attributes + values. */
1118
- updateOrInsert(attributes: Row, values?: Row): Promise<boolean>;
1235
+ chaperone(relation?: string): this;
1236
+ /** Laravel's inverse(): chaperone() under its other name. */
1237
+ inverse(relation?: string): this;
1238
+ withoutChaperone(): this;
1239
+ withoutInverse(): this;
1240
+ getInverseRelationship(): string | undefined;
1241
+ /** The first of the possible names that is a relation of the related model. */
1242
+ protected guessInverseRelation(): string | undefined;
1243
+ /** Laravel's candidates: the morph name, the foreign key without the parent's key, the parent's class, owner, parent. */
1244
+ protected getPossibleInverseRelations(): string[];
1245
+ /** Sets the parent on a related model, when chaperone() named the relation. */
1246
+ protected applyInverseRelationToModel<M extends R | null | undefined>(model: M, parent?: P): M;
1247
+ protected applyInverseRelationToMany(models: R[], parent?: P): R[];
1248
+ /** The relation query's rows (get(), first(), paginate(), …), pointing back at the parent with chaperone(). */
1249
+ runSelect(): Promise<R[]>;
1250
+ addConstraints(): void;
1251
+ addEagerConstraints(models: P[]): void;
1252
+ /** Related models grouped by their foreign key, as strings: bigint and integer keys compare equal. */
1253
+ protected buildDictionary(results: R[]): Map<string, R[]>;
1254
+ /** New related models get the parent's key (and type): post.comments().create({ body }) sets post_id. */
1255
+ newModelInstance(attributes?: Row): R;
1256
+ /** Sets the foreign key (and type) on an existing model and saves it. */
1257
+ save(model: R): Promise<R>;
1258
+ protected setForeignAttributes(model: R): R;
1259
+ saveMany(models: Iterable<R>): Promise<R[]>;
1260
+ /** One related model per record, in the related model's Eloquent collection. */
1261
+ createMany(records: Row[]): Promise<EloquentCollection<R>>;
1262
+ protected eagerPartitionColumn(): string;
1263
+ getRelationExistenceQuery(query: Builder$1<R>, _parentQuery: Builder$1<P>, columns?: ColumnRef[]): Builder$1<R>;
1264
+ }
1265
+
1266
+ /** post.comments(): many related rows hold the parent's key. */
1267
+ declare class HasMany<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, EloquentCollection<R>> {
1268
+ getResults(): Promise<EloquentCollection<R>>;
1269
+ initRelation(models: P[], relation: string): P[];
1270
+ match(models: P[], results: R[], relation: string): P[];
1271
+ }
1272
+
1273
+ /**
1274
+ * Related rows reached through an intermediate model: country.posts() → hasManyThrough(Post, User):
1275
+ * posts join users on users.id = posts.user_id where users.country_id = countries.id.
1276
+ */
1277
+ declare class HasManyThrough<R extends Model, P extends Model = Model, T extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {
1278
+ readonly throughParent: T;
1279
+ readonly firstKey: string;
1280
+ readonly secondKey: string;
1281
+ readonly localKey: string;
1282
+ readonly secondLocalKey: string;
1283
+ /** The through key of each loaded model (kept off its attributes, so it never reaches toJSON()). */
1284
+ private readonly throughKeys;
1119
1285
  /**
1120
- * Inserts rows, updating `update` (default: every inserted column except uniqueBy) when a row already exists.
1121
- * uniqueBy must be a primary key or unique index (Postgres and SQLite need it for ON CONFLICT).
1286
+ * The through table's alias when it is the related table too (a person's grandchildren, through their children):
1287
+ * every query of the relation reads it under this name, its keys and soft deletes included.
1122
1288
  */
1123
- upsert(values: Row | Row[], uniqueBy: string[], update?: string[]): Promise<number>;
1124
- increment(column: string, amount?: number, extra?: Row): Promise<number>;
1125
- decrement(column: string, amount?: number, extra?: Row): Promise<number>;
1126
- delete(id?: unknown): Promise<number>;
1127
- truncate(): Promise<void>;
1289
+ private readonly throughAlias;
1128
1290
  /**
1129
- * Paginates with a total count (two queries: count, then the page). The page comes from ?page= on the current
1130
- * request unless given: DB.table('users').orderBy('id').paginate(15).
1291
+ * @param firstKey on the through table, pointing at the far parent ('users.country_id')
1292
+ * @param secondKey on the related table, pointing at the through model ('posts.user_id')
1293
+ * @param localKey on the far parent ('countries.id')
1294
+ * @param secondLocalKey on the through model ('users.id')
1131
1295
  */
1132
- paginate(perPage?: number, columns?: ColumnRef[], pageName?: string, page?: number): Promise<LengthAwarePaginator<T>>;
1133
- /** Paginates without a count: fetches perPage + 1 rows to know whether there is a next page. */
1134
- simplePaginate(perPage?: number, columns?: ColumnRef[], pageName?: string, page?: number): Promise<Paginator<T>>;
1135
- /**
1136
- * Paginates by the ordered columns' values instead of an offset. Needs an orderBy (Eloquent adds the primary key);
1137
- * the cursor comes from ?cursor= on the current request unless given.
1138
- */
1139
- cursorPaginate(perPage?: number, columns?: ColumnRef[], cursorName?: string, cursor?: Cursor | string): Promise<CursorPaginator<T>>;
1296
+ constructor(related: R, farParent: P, throughParent: T, firstKey: string, secondKey: string, localKey: string, secondLocalKey: string);
1297
+ /** The through table to join: `users`, or `users as <alias>`. */
1298
+ private throughTable;
1299
+ /** A through column, qualified by the through table or by its alias. */
1300
+ private throughColumn;
1301
+ /** users.country_id */
1302
+ getQualifiedFirstKeyName(): string;
1303
+ /** posts.user_id */
1304
+ getQualifiedForeignKeyName(): string;
1305
+ /** users.id */
1306
+ getQualifiedParentKeyName(): string;
1307
+ /** countries.id */
1308
+ getQualifiedLocalKeyName(): string;
1309
+ addConstraints(): void;
1310
+ addEagerConstraints(models: P[]): void;
1311
+ /** Selects the related columns plus the through key, then moves the key off the attributes. */
1312
+ runSelect(): Promise<R[]>;
1313
+ /** An eager limit() or offset() applies to each far parent, by the through table's key to it (Laravel 11). */
1314
+ protected eagerPartitionColumn(): string;
1315
+ getResults(): Promise<EloquentCollection<R>>;
1316
+ getEager(): Promise<EloquentCollection<R>>;
1317
+ initRelation(models: P[], relation: string): P[];
1318
+ match(models: P[], results: R[], relation: string): P[];
1140
1319
  /**
1141
- * Runs the query page by page and passes each chunk to callback. Return false to stop. Needs an orderBy, so that
1142
- * pages don't overlap. Don't update the ordered column inside the callback; use chunkById() for that.
1320
+ * The query of has()/withCount(), as Laravel's ...ForSelfRelation and ...ForThroughSelfRelation: a related table that
1321
+ * is the parent's is read under an alias, and so is a through table that is the parent's (or the related one).
1143
1322
  */
1144
- chunk(count: number, callback: (results: Collection<T>, page: number) => unknown): Promise<boolean>;
1145
- /** Chunks by comparing the key (where id > last id), so it is safe to update or delete rows inside the callback. */
1146
- chunkById(count: number, callback: (results: Collection<T>, page: number) => unknown, column?: string, alias?: string): Promise<boolean>;
1147
- /** Calls callback for every row, fetching `count` rows per query. Return false to stop. */
1148
- each(callback: (item: T, index: number) => unknown, count?: number): Promise<boolean>;
1149
- /** A LazyCollection that runs one query per chunk as it is iterated: for await (const user of query.lazy()). */
1150
- lazy(chunkSize?: number): LazyCollection<T>;
1151
- /** Like lazy(), but pages by key, so rows can be updated while iterating. */
1152
- lazyById(chunkSize?: number, column?: string, alias?: string): LazyCollection<T>;
1153
- /** where column > lastId order by column limit perPage (existing orders on the column are replaced). */
1154
- forPageAfterId(perPage?: number, lastId?: unknown, column?: string): this;
1155
- /** chunk() and lazy() need a stable order. Eloquent orders by the primary key instead of throwing. */
1156
- protected enforceOrderBy(): void;
1157
- /** The key chunkById()/lazyById() use by default. Eloquent uses the model's key. */
1158
- protected defaultKeyName(): string;
1159
- /** The page size when none is given. Eloquent uses the model's perPage. */
1160
- protected defaultPerPage(): number;
1161
- /** Laravel's get($columns): only applies when no columns were selected yet. */
1162
- private withColumns;
1163
- /** The column orders cursor pagination compares on; reversed (in the query too) when paging backwards. */
1164
- private ordersForCursor;
1165
- /** (a > ?) or (a = ? and (b > ? or (b = ? and …))), Laravel's cursor conditions. */
1166
- private whereCursor;
1167
- /** The compiled SQL (placeholders included), for debugging and tests. */
1168
- toSql(): string;
1169
- getBindings(): unknown[];
1170
- clone(): Builder$1<T>;
1171
- /** A fresh builder on the same connection and table (for nested where groups). */
1172
- newQuery(): Builder$1<Row>;
1173
- requireTable(): string | Expression;
1174
- private subQuery;
1175
- private addNested;
1176
- private addWhere;
1177
- /** Laravel's addDateBasedWhere(): one value means '='; the operator is checked against the whitelist. */
1178
- private addDateBasedWhere;
1179
- private pushNull;
1323
+ getRelationExistenceQuery(query: Builder$1<R>, _parentQuery: Builder$1<P>, columns?: ColumnRef[]): Builder$1<R>;
1180
1324
  }
1181
- type JoinType = 'inner' | 'left' | 'right' | 'cross';
1182
- /** The `on …` part of a join. `where()` on a join binds a value; `on()` compares columns. */
1183
- declare class JoinClause extends Builder$1<Row> {
1184
- readonly joinType: JoinType;
1185
- readonly table: string | Expression;
1186
- constructor(parent: Builder$1<unknown>, joinType: JoinType, table: string | Expression);
1187
- on(first: ColumnRef, operator: string, second?: ColumnRef, boolean?: WhereBoolean): this;
1188
- orOn(first: ColumnRef, operator: string, second?: ColumnRef): this;
1325
+
1326
+ /** user.profile(): one related row holds the parent's key. */
1327
+ declare class HasOne<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, R | null> {
1328
+ getResults(): Promise<R | null>;
1329
+ initRelation(models: P[], relation: string): P[];
1330
+ match(models: P[], results: R[], relation: string): P[];
1189
1331
  }
1190
1332
 
1191
- /** Laravel's storage format ('Y-m-d H:i:s'), in UTC. */
1192
- declare function formatDateTime(date: Date): string;
1193
- declare function formatDate(date: Date): string;
1194
- /**
1195
- * Parses a stored date/time as UTC. Accepts Dates, epoch milliseconds, 'Y-m-d', 'Y-m-d H:i:s' and ISO strings
1196
- * (the last two with or without a zone suffix; a missing zone means UTC).
1197
- */
1198
- declare function parseDateTime(value: unknown): Date;
1199
- /** Normalizes one binding for the driver: booleans, dates, JSON and undefined. */
1200
- declare function prepareValue(value: unknown, driver: DriverName): unknown;
1333
+ /** post.comments() → morphMany(Comment, 'commentable'): comments.commentable_id + commentable_type = 'Post'. */
1334
+ declare class MorphMany<R extends Model, P extends Model = Model> extends HasMany<R, P> {
1335
+ /**
1336
+ * @param morphType the qualified type column ('comments.commentable_type')
1337
+ * @param foreignKey the qualified id column ('comments.commentable_id')
1338
+ */
1339
+ constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string);
1340
+ }
1201
1341
 
1202
- /** `config('database')`, in Laravel's config/database.php shape. */
1203
- interface DatabaseConfig {
1204
- default: string;
1205
- connections: Record<string, ConnectionConfig>;
1206
- /** Laravel 11: { table: 'migrations' }. A plain string (older Laravel) is accepted too. */
1207
- migrations?: {
1208
- table?: string;
1209
- } | string;
1342
+ /** user.image() → morphOne(Image, 'imageable'): images.imageable_id + imageable_type = 'User'. */
1343
+ declare class MorphOne<R extends Model, P extends Model = Model> extends HasOne<R, P> {
1344
+ constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string);
1210
1345
  }
1346
+
1211
1347
  /**
1212
- * The DatabaseManager contract: named connections from config('database'), created on first use and cached.
1213
- * Everything a connection does is also available here and runs on the default connection, as with Laravel's DB facade.
1214
- * Named DatabaseManagerImpl so it never shadows the DatabaseManager token when both are re-exported.
1348
+ * comment.commentable() → morphTo('commentable'): the parent's class comes from commentable_type (a morph map alias
1349
+ * or a class name) and its key from commentable_id. Eager loading runs one query per distinct type.
1215
1350
  */
1216
- declare class DatabaseManagerImpl implements DatabaseManager {
1217
- private readonly config;
1218
- private readonly connections;
1219
- private defaultName;
1220
- /** Pass the config, or a function that reads it (the provider reads config('database') lazily). */
1221
- constructor(config: DatabaseConfig | (() => DatabaseConfig));
1222
- private settings;
1223
- /** A connection by name (default: config('database.default')). */
1224
- connection(name?: string): Connection;
1225
- getDefaultConnection(): string;
1226
- /** Overrides config('database.default'); undefined clears the override. */
1227
- setDefaultConnection(name: string | undefined): void;
1351
+ declare class MorphTo<R extends Model = Model, P extends Model = Model> extends BelongsTo<R, P> {
1352
+ readonly morphTypeColumn: string;
1353
+ readonly ownerKeyOverride: string | undefined;
1354
+ /** Parents grouped by type, then by id, while eager loading. */
1355
+ private dictionary;
1356
+ /** The stored type each eager result was loaded for (an alias or a class name), for match(). */
1357
+ private resultTypes;
1228
1358
  /**
1229
- * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), then restores the previous
1230
- * override, or none, so the default follows config('database.default') again. Without a name, just runs it.
1359
+ * @param related an instance of the current type's class (the child's own class when the type is empty)
1360
+ * @param morphType the type column on the child ('commentable_type')
1361
+ * @param ownerKey the key on the parent (default: each class's primary key)
1231
1362
  */
1232
- usingConnection<T>(name: string | undefined, callback: () => Promise<T>): Promise<T>;
1233
- /** The connections opened so far. */
1234
- getConnections(): Record<string, Connection>;
1235
- /** The migrations table name (config('database.migrations.table'), default 'migrations'). */
1236
- migrationsTable(): string;
1237
- /** Closes a connection's pool and forgets it; the next connection(name) opens a new one. */
1238
- disconnect(name?: string): Promise<void>;
1239
- /** Laravel's purge(): the same as disconnect() here. */
1240
- purge(name?: string): Promise<void>;
1241
- /** Closes every open connection (app shutdown, the end of a test). */
1242
- disconnectAll(): Promise<void>;
1243
- /** The default connection's schema builder; Schema.connection(name) switches connections through this manager. */
1244
- getSchemaBuilder(): SchemaBuilder;
1245
- /** A raw SQL fragment: DB.raw('count(*) as total'). */
1246
- raw(value: string, bindings?: readonly unknown[]): Expression;
1247
- getName(): string;
1248
- getDriverName(): DriverName;
1249
- kysely(): ReturnType<Connection['kysely']>;
1250
- table<T = Row>(table: string | Expression): Builder$1<T>;
1251
- query<T = Row>(): Builder$1<T>;
1252
- select<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T[]>;
1253
- /** The first row of a raw select, or undefined. */
1254
- selectOne<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T | undefined>;
1255
- /** Raw insert. Returns true, like Laravel's DB::insert(). */
1256
- insert(query: string, bindings?: readonly unknown[]): Promise<boolean>;
1257
- /** Raw update; returns the number of affected rows. */
1258
- update(query: string, bindings?: readonly unknown[]): Promise<number>;
1259
- /** Raw delete; returns the number of affected rows. */
1260
- delete(query: string, bindings?: readonly unknown[]): Promise<number>;
1261
- statement(query: string, bindings?: readonly unknown[]): Promise<void>;
1262
- affectingStatement(query: string, bindings?: readonly unknown[]): Promise<number>;
1263
- transaction<R>(fn: (connection: Connection) => Promise<R>): Promise<R>;
1264
- beginTransaction(): Promise<void>;
1265
- commit(): Promise<void>;
1266
- rollBack(): Promise<void>;
1267
- transactionLevel(): number;
1268
- enableQueryLog(): void;
1269
- disableQueryLog(): void;
1270
- getQueryLog(): LoggedQuery[];
1271
- flushQueryLog(): void;
1363
+ constructor(related: R, child: P, foreignKey: string, morphTypeColumn: string, ownerKeyOverride: string | undefined, relationName: string);
1364
+ getMorphType(): string;
1365
+ addConstraints(): void;
1366
+ getResults(): Promise<R | null>;
1367
+ /** Groups the children by type and id; the queries run in getEager(). */
1368
+ addEagerConstraints(models: P[]): void;
1369
+ /** One query per type, with this relation's constraints and nested eager loads. */
1370
+ getEager(): Promise<Collection<R>>;
1371
+ match(models: P[], results: R[], relation: string): P[];
1372
+ /** Points the child at `model`: sets the id and the type columns and the loaded relation. */
1373
+ associate(model: R | null): P;
1374
+ getRelationExistenceQuery(): Builder$1<R>;
1272
1375
  }
1273
1376
 
1274
- /**
1275
- * The DB facade: DB.table('users').get(), DB.transaction(fn), DB.connection('pgsql'), DB.kysely().
1276
- * DB.raw() works without an application (it only builds an Expression).
1277
- */
1278
- declare const DB: _orieljs_support.Facade<DatabaseManagerImpl, {
1279
- raw: typeof raw;
1280
- }>;
1281
- /** The Schema facade's binding: the default connection's SchemaBuilder (DatabaseServiceProvider binds it). */
1282
- declare const SchemaBuilderToken: Token<SchemaBuilder>;
1283
- /** The Schema facade: Schema.create('posts', (t) => { … }), Schema.table(…), Schema.dropIfExists(…). */
1284
- declare const Schema: _orieljs_support.Facade<SchemaBuilder, object>;
1285
-
1286
- /**
1287
- * A custom cast (Laravel's CastsAttributes): get() turns the stored value into what the model exposes, set() turns
1288
- * an assigned value back into what is stored.
1289
- */
1290
- interface CastsAttributes<TGet = unknown, TSet = TGet> {
1291
- get(model: object, key: string, value: unknown, attributes: Row): TGet;
1292
- set(model: object, key: string, value: TSet, attributes: Row): unknown;
1377
+ /** A global scope class (Laravel's Scope): its apply() adds constraints to every query of the model. */
1378
+ interface Scope {
1379
+ apply(builder: Builder$1<any>, model: Model): void;
1293
1380
  }
1294
- /** A TypeScript enum object (string or numeric) used as a cast: casts = { status: PostStatus }. */
1295
- type EnumLike = Record<string, string | number>;
1296
- type BuiltInCast = 'int' | 'integer' | 'float' | 'double' | 'real' | 'string' | 'bool' | 'boolean' | 'array' | 'json' | 'object' | 'collection' | 'date' | 'datetime' | 'immutable_date' | 'immutable_datetime' | 'timestamp' | 'hashed' | `decimal:${number}`;
1297
- type CastDefinition = BuiltInCast | EnumLike | CastsAttributes | (new () => CastsAttributes);
1298
- /** The values of a TypeScript enum. Numeric enums also map values back to names; those reverse entries are skipped. */
1299
- declare function enumValues(cast: EnumLike): Array<string | number>;
1300
- declare const isJsonCast: (cast: CastDefinition | undefined) => boolean;
1301
- declare const isDateCast: (cast: CastDefinition | undefined) => boolean;
1302
- /** Laravel's castAttribute(): the stored value → the value the model exposes. null stays null (except custom casts). */
1303
- declare function castGet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
1304
- /** The value assigned to a cast attribute → the value stored in the model's attributes (and later bound). */
1305
- declare function castSet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
1306
- /**
1307
- * Laravel's originalIsEquivalent(): does the stored value still mean the same thing as the original?
1308
- * Keeps save() from writing columns whose value only changed representation (1 vs true, '5' vs 5, same instant).
1309
- */
1310
- declare function isEquivalent(cast: CastDefinition | undefined, current: unknown, original: unknown, model: object, key: string, className: string): boolean;
1381
+ type ScopeCallback = (builder: Builder$1<any>) => void;
1382
+ type GlobalScope = Scope | ScopeCallback;
1383
+
1384
+ type Instance<C extends typeof Model> = InstanceType<C>;
1385
+ type ScopeClass = abstract new (...args: never[]) => unknown;
1311
1386
 
1312
1387
  /**
1313
- * Laravel's Eloquent collection: what every query, relation and eager load of models returns. It is a support
1314
- * Collection (methods that keep the items keep this class; map() and the other type-changing methods return a plain
1315
- * Collection) with the model-aware methods: find() by key, load() and loadCount() for every model at once, fresh(),
1316
- * modelKeys(), toQuery(), and diff()/intersect()/unique()/only()/except()/merge() that compare models by key.
1388
+ * Eloquent's Model: an Active Record over one table.
1389
+ *
1390
+ * Config lives in instance fields, as in Laravel: `protected fillable = ['title']`, `protected casts = {…}`,
1391
+ * `protected hidden = ['password']`, `protected table = 'posts'`. Attribute columns are never declared as class
1392
+ * fields (they would shadow the Proxy); their types come from `oriel model:types`, or from `declare title: string`.
1393
+ * `new Post()` takes no arguments: use Post.make(attrs), Post.create(attrs) or new Post().fill(attrs).
1317
1394
  */
1318
- declare class EloquentCollection<M extends Model = Model> extends Collection<M> {
1319
- /** The model with this key (or this model's key), else the default; with several keys, those models. */
1320
- find(key: readonly unknown[] | Collection<unknown>): this;
1321
- find(key: unknown): M | undefined;
1322
- find<D>(key: unknown, defaultValue: D): M | D;
1323
- /** find(), or ModelNotFoundError naming the missing keys. */
1324
- findOrFail(keys: readonly unknown[] | Collection<unknown>): this;
1325
- findOrFail(key: unknown): M;
1326
- /** The primary keys, in order. */
1327
- modelKeys(): unknown[];
1328
- /** The models keyed by their primary key (as text). */
1329
- getDictionary(items?: Iterable<M>): Record<string, M>;
1330
- /** The same models in a plain Collection. */
1331
- toBase(): Collection<M>;
1332
- /** Whether a model with this key (or this model) is in the collection; the other forms are Collection's. */
1333
- contains(key: keyof M & string, value: unknown): boolean;
1334
- contains(key: (keyof M & string) | ((item: M) => unknown), operator: Operator$1, value: unknown): boolean;
1335
- contains(callback: (item: M) => boolean): boolean;
1336
- contains(value: unknown): boolean;
1337
- /** Collection's containsStrict(): a model matches only itself (no key matching). */
1338
- containsStrict(key: keyof M & string, value: unknown): boolean;
1339
- containsStrict(callback: (item: M) => boolean): boolean;
1340
- containsStrict(value: unknown): boolean;
1341
- /** Collection's doesntContainStrict(): a model matches only itself (no key matching). */
1342
- doesntContainStrict(key: keyof M & string, value: unknown): boolean;
1343
- doesntContainStrict(callback: (item: M) => boolean): boolean;
1344
- doesntContainStrict(value: unknown): boolean;
1345
- /** Eager loads relations onto every model, one query per relation: await posts.load('author', 'comments.author'). */
1346
- load(...relations: EagerLoadSpec[]): Promise<this>;
1347
- /** Loads only the relations that aren't loaded yet; nested paths are followed into the loaded relations. */
1348
- loadMissing(...relations: string[]): Promise<this>;
1349
- /** Adds <relation>_count attributes to every model with one query: await posts.loadCount('comments'). */
1350
- loadCount(...relations: EagerLoadSpec[]): Promise<this>;
1395
+ declare class Model implements ModelInstance {
1396
+ static CREATED_AT: string | null;
1397
+ static UPDATED_AT: string | null;
1398
+ static DELETED_AT: string;
1399
+ /** The table (default: the snake_case plural of the class name: BlogPost → blog_posts). */
1400
+ protected table: string | undefined;
1401
+ protected primaryKey: string;
1402
+ protected keyType: 'int' | 'string';
1403
+ incrementing: boolean;
1404
+ /** Attributes that fill()/create() may set. */
1405
+ protected fillable: string[];
1406
+ /** Attributes fill() never sets. ['*'] (the default) guards everything that isn't fillable. */
1407
+ protected guarded: string[];
1408
+ protected casts: Readonly<Record<string, CastDefinition>>;
1409
+ /** Left out of toArray()/toJSON(). */
1410
+ protected hidden: string[];
1411
+ /** When non-empty, only these are in toArray()/toJSON(). */
1412
+ protected visible: string[];
1413
+ /** Accessor-only attributes added to toArray()/toJSON(). */
1414
+ protected appends: string[];
1415
+ timestamps: boolean;
1416
+ /** Turns on soft deletes (Laravel's `use SoftDeletes`): deleted_at instead of a real delete. */
1417
+ protected softDeletes: boolean;
1418
+ /** The connection name (default: config('database.default')). */
1419
+ protected connection: string | undefined;
1420
+ protected perPage: number;
1421
+ /** Relations every query of this model eager loads (Laravel's $with). */
1422
+ protected with: string[];
1423
+ /** Relation counts every query of this model adds (Laravel's $withCount). */
1424
+ protected withCount: string[];
1425
+ exists: boolean;
1426
+ wasRecentlyCreated: boolean;
1427
+ protected forceDeleting: boolean;
1428
+ protected attributes: Row;
1429
+ protected original: Row;
1430
+ protected changes: Row;
1431
+ protected relations: Record<string, unknown>;
1432
+ /** Decoded json/array/object/collection values, so in-place changes are seen by save(). */
1433
+ protected castCache: Map<string, {
1434
+ raw: unknown;
1435
+ value: unknown;
1436
+ }>;
1437
+ /** Attributes with the hashed cast that were assigned a value since the last save; save() hashes them. */
1438
+ protected pendingHashes: Set<string>;
1439
+ constructor();
1440
+ /** Runs booting()/booted() once per class, the first time the class is instantiated. */
1441
+ static bootIfNotBooted(): void;
1351
1442
  /**
1352
- * Laravel's loadAggregate(): withAggregate() for models already loaded, with one query for the whole collection.
1353
- * The values become clean attributes (with their casts: loadExists() gives booleans).
1443
+ * Framework hook: installs the static scope proxies (Post.published()) and, with `softDeletes = true`, the soft
1444
+ * delete scope. Overrides must call super.boot().
1354
1445
  */
1355
- loadAggregate(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): Promise<this>;
1356
- /** Adds <relation>_sum_<column> to every model: await users.loadSum('orders', 'price'). */
1357
- loadSum(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
1358
- loadAvg(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
1359
- loadMin(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
1360
- loadMax(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
1361
- /** Adds a boolean <relation>_exists to every model. */
1362
- loadExists(...relations: EagerLoadSpec[]): Promise<this>;
1363
- /** The models as they are in the database now (without global scopes), with relations loaded; deleted ones drop out. */
1364
- fresh(...relations: EagerLoadSpec[]): Promise<this>;
1365
- /** The models whose keys aren't in the given models. */
1366
- diff(items: Iterable<M>): this;
1367
- /** The models whose keys are also in the given models. */
1368
- intersect(items: Iterable<M>): this;
1369
- /** One model per key (the last instance, at the first one's place); with a key or callback, Collection's unique(). */
1370
- unique(key?: (keyof M & string) | ((item: M) => unknown)): this;
1371
- /** The models with these keys, in the collection's order. */
1372
- only(...keys: unknown[]): this;
1373
- /** The models without these keys, in the collection's order. */
1374
- except(...keys: unknown[]): this;
1375
- /** Adds the given models, replacing the ones with the same key. */
1376
- merge(items: Iterable<M>): this;
1377
- makeHidden(...attributes: Array<string | string[]>): this;
1378
- makeVisible(...attributes: Array<string | string[]>): this;
1379
- setVisible(visible: string[]): this;
1380
- setHidden(hidden: string[]): this;
1381
- append(...attributes: Array<string | string[]>): this;
1382
- /** A query of exactly these models (where key in …), for mass updates: await posts.toQuery().update({ … }). */
1383
- toQuery(): Builder<M>;
1384
- }
1385
-
1386
- /**
1387
- * A relation is the related model's query builder, constrained to the parent: post.comments() is a
1388
- * Builder<Comment> with `where comments.post_id = ?`, so every builder method (where, orderBy, paginate, a local
1389
- * scope, …) works on it. Subclasses add eager loading (addEagerConstraints/initRelation/match) and the existence
1390
- * queries behind has()/whereHas()/withCount().
1391
- */
1392
- declare abstract class Relation<R extends Model = Model, P extends Model = Model, Result = unknown> extends Builder<R> {
1393
- readonly parent: P;
1394
- /** The name the relation is loaded under (set when resolved by name, for eager loading and associate()). */
1395
- relationName: string | undefined;
1396
- /** Laravel's Relation::morphMap(): { post: Post } stores 'post' instead of 'Post' in *_type columns. */
1397
- static morphMap(map?: Record<string, typeof Model>, merge?: boolean): Record<string, typeof Model>;
1398
- static getMorphedModel(alias: string): typeof Model | undefined;
1399
- protected constructor(related: R, parent: P);
1400
- getParent(): P;
1401
- getRelated(): R;
1402
- /** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */
1403
- protected init(): void;
1404
- /** The constraints for one parent: where comments.post_id = post.id. */
1405
- abstract addConstraints(): void;
1406
- /** The constraints for many parents: where comments.post_id in (…). */
1407
- abstract addEagerConstraints(models: P[]): void;
1408
- /** Sets the empty value (null or an empty collection) on every parent. */
1409
- abstract initRelation(models: P[], relation: string): P[];
1410
- /** Distributes the eagerly loaded results to their parents. */
1411
- abstract match(models: P[], results: R[], relation: string): P[];
1412
- /** The relation's value for this parent (a model, null or a collection). */
1413
- abstract getResults(): Promise<Result>;
1414
- /** The query of has()/whereHas(): related rows that belong to the outer query's current row. */
1415
- abstract getRelationExistenceQuery(query: Builder<R>, parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1416
- /** Runs the eager query. */
1417
- getEager(): Promise<Collection<R>>;
1418
- /** select count(*) … for withCount() and has('comments', '>=', 3). */
1419
- getRelationExistenceCountQuery(query: Builder<R>, parentQuery: Builder<P>): Builder<R>;
1420
- /** The distinct non-null values of `key` on the models (the eager whereIn list). */
1421
- protected keysOf(models: Model[], key: string): unknown[];
1422
- }
1423
-
1424
- /** A global scope class (Laravel's Scope): its apply() adds constraints to every query of the model. */
1425
- interface Scope {
1426
- apply(builder: Builder<any>, model: Model): void;
1427
- }
1428
- type ScopeCallback = (builder: Builder<any>) => void;
1429
- type GlobalScope = Scope | ScopeCallback;
1430
-
1431
- /**
1432
- * A model's attribute types. `oriel model:types` adds a phantom `$attributes?: { … }` member to each model through
1433
- * declaration merging; without it every attribute is `unknown`.
1434
- */
1435
- type Attributes<M> = M extends {
1436
- $attributes?: infer A;
1437
- } ? (unknown extends A ? Row : NonNullable<A>) : Row;
1438
- /**
1439
- * The column names a builder of M accepts: the generated attribute names plus any qualified `table.column`.
1440
- * Without generated types, any string.
1441
- */
1442
- type Column<M> = M extends {
1443
- $attributes?: infer A;
1444
- } ? unknown extends A ? string : (keyof NonNullable<A> & string) | `${string}.${string}` : string;
1445
- /** A model class: constructible with no arguments, with Model's statics. */
1446
- type ModelClass<M extends Model = Model> = (new () => M) & Omit<typeof Model, 'prototype'>;
1447
- type AnyScope = (query: any, ...args: any[]) => unknown;
1448
- /** 'scopePublished' → 'published'. */
1449
- type ScopeName<K> = K extends `scope${infer Name}` ? Uncapitalize<Name> : never;
1450
- /** The local scopes of a model class as builder methods: static scopeOfType(q, type) → query.ofType(type). */
1451
- type Scopes<C extends typeof Model> = {
1452
- [K in keyof C as ScopeName<K>]: C[K] extends (query: never, ...args: infer A) => unknown ? (...args: A) => ModelBuilder<C> : never;
1453
- };
1454
- /** Post.query(): the Eloquent builder of Post, plus Post's local scopes. */
1455
- type ModelBuilder<C extends typeof Model> = Builder<InstanceType<C>> & Scopes<C>;
1456
- /** The static scope proxy type used by generated types: Post.published(). */
1457
- type ScopeStatic<C extends typeof Model, K extends keyof C> = C[K] extends AnyScope ? C[K] extends (query: never, ...args: infer A) => unknown ? (...args: A) => ModelBuilder<C> : never : never;
1458
- /** The arguments where() accepts on a builder of M (column names are checked when types are generated). */
1459
- type WhereArgs<M, Q> = [column: Column<M> | Expression, value: unknown] | [column: Column<M> | Expression, operator: Operator | string, value: unknown] | [conditions: Row] | [callback: (query: Q) => unknown];
1460
- /** The names of a model's relation methods (methods returning a relation). */
1461
- type RelationNames<M> = {
1462
- [K in keyof M]: M[K] extends () => {
1463
- getResults(): Promise<any>;
1464
- } ? K : never;
1465
- }[keyof M] & string;
1466
- /** The loaded value of a relation: what its getResults() resolves to (a model or null, or a Collection). */
1467
- type RelationValue<M, K extends keyof M> = M[K] extends () => {
1468
- getResults(): Promise<infer T>;
1469
- } ? T : never;
1470
-
1471
- type AnyRelation = Relation<any, any, any>;
1472
- /** A constraint on an eager load, withCount() or whereHas(): (query) => query.where(…). */
1473
- type RelationConstraint = (query: AnyRelation) => unknown;
1474
- /** with('author'), with(['author', 'comments.user']), with({ comments: (q) => q.latest() }), with('author:id,name'). */
1475
- type EagerLoadSpec = string | string[] | Record<string, RelationConstraint>;
1476
- type AnyFunction = (...args: unknown[]) => unknown;
1477
- /**
1478
- * Eloquent's builder: the query builder of one model class. Rows come back as hydrated models, global scopes are
1479
- * applied when the query runs (grouped so an orWhere can't escape them), and unknown methods call the model's local
1480
- * scopes. Everything the query builder does (pagination, chunk, lazy, …) returns models here.
1481
- */
1482
- declare class Builder<M extends Model = Model> extends Builder$1<M> {
1483
- readonly model: M;
1484
- protected scopes: Map<string, GlobalScope>;
1485
- protected removedScopes: string[];
1486
- protected eagerLoad: Map<string, RelationConstraint | undefined>;
1487
- /** Casts for the selected columns (withCasts()), merged into every model this query hydrates. */
1488
- protected selectCasts: Record<string, CastDefinition>;
1489
- constructor(model: M);
1490
- getModel(): M;
1491
- /** The model class's static scope<Name> method for a builder method name, if any. */
1492
- localScope(name: string): AnyFunction | undefined;
1493
- /** Runs a scope; the wheres it adds are grouped when they contain an "or" (Laravel's callScope). */
1494
- callScope(scope: (query: this) => unknown): this;
1495
- withGlobalScope(name: string, scope: GlobalScope): this;
1496
- /** Removes a global scope by name or Scope class. */
1497
- withoutGlobalScope(scope: string | (abstract new (...args: never[]) => unknown)): this;
1498
- /** Removes every global scope, or the given ones. */
1499
- withoutGlobalScopes(scopes?: Array<string | (abstract new (...args: never[]) => unknown)>): this;
1500
- removedScopeNames(): string[];
1501
- /** A copy of this query with every global scope applied (Laravel's applyScopes()). */
1502
- applyScopes(): this;
1503
- /** Groups [0, count) and [count, …) separately when either contains an "or", so scopes combine with "and". */
1504
- protected addNewWheresWithinGroup(count: number): void;
1505
- private groupWhereSlice;
1506
- where(column: Column<M> | Expression, value: unknown): this;
1507
- where(column: Column<M> | Expression, operator: Operator | string, value: unknown): this;
1508
- where(conditions: Row): this;
1509
- where(callback: (query: this) => unknown): this;
1510
- orWhere(column: Column<M> | Expression, value: unknown): this;
1511
- orWhere(column: Column<M> | Expression, operator: Operator | string, value: unknown): this;
1512
- orWhere(conditions: Row): this;
1513
- orWhere(callback: (query: this) => unknown): this;
1514
- whereIn(column: Column<M> | Expression, values: readonly unknown[] | Builder$1<unknown>): this;
1515
- whereNotIn(column: Column<M> | Expression, values: readonly unknown[] | Builder$1<unknown>): this;
1516
- whereNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this;
1517
- whereNotNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this;
1518
- whereBetween(column: Column<M> | Expression, values: readonly [unknown, unknown]): this;
1519
- whereDate(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1520
- orWhereDate(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1521
- whereTime(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1522
- orWhereTime(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1523
- whereDay(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1524
- orWhereDay(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1525
- whereMonth(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1526
- orWhereMonth(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1527
- whereYear(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1528
- orWhereYear(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1529
- whereLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean, boolean?: WhereBoolean, not?: boolean): this;
1530
- orWhereLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean): this;
1531
- whereNotLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean, boolean?: WhereBoolean): this;
1532
- orWhereNotLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean): this;
1533
- orderBy(column: Column<M> | Expression, direction?: Direction | Uppercase<Direction>): this;
1534
- /** Newest first by the model's created_at column (or the given one). */
1535
- latest(column?: Column<M> | Expression): this;
1536
- oldest(column?: Column<M> | Expression): this;
1537
- select(...columns: Array<Column<M> | Expression | Array<Column<M> | Expression>>): this;
1538
- /** where key = id (or key in ids). */
1539
- whereKey(id: unknown): this;
1540
- whereKeyNot(id: unknown): this;
1541
- /** The models, in the model's collection (an EloquentCollection). */
1542
- get(): Promise<EloquentCollection<M>>;
1543
- protected newCollection(models: M[]): EloquentCollection<M>;
1544
- /** chunk() with each chunk in the model's collection. */
1545
- chunk(count: number, callback: (models: EloquentCollection<M>, page: number) => unknown): Promise<boolean>;
1546
- chunkById(count: number, callback: (models: EloquentCollection<M>, page: number) => unknown, column?: string, alias?: string): Promise<boolean>;
1547
- /** Runs the query, hydrates models, fires their retrieved events and eager loads the with() relations. */
1548
- runSelect(): Promise<M[]>;
1446
+ static boot(): void;
1447
+ /** Runs before boot(). */
1448
+ static booting(): void;
1449
+ /** Register global scopes and model event listeners here: static booted() { this.addGlobalScope(…) }. */
1450
+ static booted(): void;
1549
1451
  /**
1550
- * Relations to load with the results, one query per relation (and per nesting level):
1551
- * with('author'), with('comments.author'), with({ comments: (q) => q.where('approved', true) }), with('author:id,name').
1452
+ * Forgets which classes are booted, and their global scopes (Laravel's clearBootedModels()), so the next use boots
1453
+ * them again: booted() re-registers its scopes and event listeners against the current application. Every new
1454
+ * application does this (DatabaseServiceProvider.register()).
1552
1455
  */
1553
- with(...relations: EagerLoadSpec[]): this;
1554
- /** Removes eager loads (including the model's default `with`). */
1555
- without(...relations: string[]): this;
1556
- getEagerLoads(): Map<string, RelationConstraint | undefined>;
1557
- /** Loads every top-level with() relation onto the models (nested ones are passed down to each relation query). */
1558
- eagerLoadRelations(models: M[]): Promise<M[]>;
1559
- /** The relation instance for a name, without its per-parent constraints. */
1560
- getRelation(name: string): AnyRelation;
1561
- protected eagerLoadRelation(models: M[], name: string, constraint: RelationConstraint | undefined): Promise<void>;
1562
- private addEagerLoad;
1563
- private relationsNestedUnder;
1456
+ static clearBootedModels(): void;
1457
+ /** One cached instance per class, used by static methods to read config (table, key, casts, …). */
1458
+ static prototypeInstance<M extends Model>(this: new () => M): M;
1459
+ /** A new, unsaved model filled with attributes (mass assignment rules apply). */
1460
+ static make<M extends Model, const T extends object = Row>(this: new () => M, attributes?: T & WriteAttributes<M, T>): M;
1564
1461
  /**
1565
- * Adds `<relation>_count` columns: withCount('comments'), withCount({ comments: (q) => q.where('approved', true) }),
1566
- * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.
1462
+ * Adds a global scope to every query of this class: addGlobalScope('published', q => …),
1463
+ * addGlobalScope(new ActiveScope()) (named after its class) or addGlobalScope(q => …).
1567
1464
  */
1568
- withCount(...relations: EagerLoadSpec[]): this;
1569
- /** Adds `<relation>_sum_<column>`: withSum('orders', 'price'), withSum({ 'orders as paid': (q) => … }, 'price'). */
1570
- withSum(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this;
1571
- /** Adds `<relation>_avg_<column>`. */
1572
- withAvg(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this;
1573
- /** Adds `<relation>_min_<column>`. */
1574
- withMin(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this;
1575
- /** Adds `<relation>_max_<column>`. */
1576
- withMax(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this;
1577
- /** Adds a boolean `<relation>_exists`: withExists('comments'). */
1578
- withExists(...relations: EagerLoadSpec[]): this;
1579
- /**
1580
- * Laravel's withAggregate(): a correlated subquery per relation, `select <fn>(<related column>) … as <alias>`, the
1581
- * alias being `<relation>_<fn>_<column>` unless the relation is named `'orders as alias'`. The relation's
1582
- * constraint and the related model's global scopes apply; orderings are dropped. 'exists' selects
1583
- * `exists (…)`, cast to a boolean. Without a function the column's first value is selected.
1465
+ static addGlobalScope(scope: Scope | ScopeCallback): string;
1466
+ static addGlobalScope(name: string, scope: GlobalScope): string;
1467
+ static hasGlobalScope(scope: string | ScopeClass): boolean;
1468
+ static getGlobalScopes(): Map<string, GlobalScope>;
1469
+ /** Registers a listener for one of this model's events ('eloquent.<event>: <Class>'). Needs an EventDispatcher. */
1470
+ static registerModelEvent<C extends typeof Model>(this: C, event: ModelEvent, callback: ModelListener<InstanceType<C>>): void;
1471
+ static retrieved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1472
+ static creating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1473
+ static created<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1474
+ static updating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1475
+ static updated<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1476
+ static saving<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1477
+ static saved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1478
+ static deleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1479
+ static deleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1480
+ static restoring<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1481
+ static restored<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1482
+ static forceDeleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1483
+ static forceDeleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
1484
+ /**
1485
+ * Registers observers: every method named after a model event (created, updating, …) becomes a listener.
1486
+ * Observer classes are resolved from the container.
1584
1487
  */
1585
- withAggregate(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): this;
1586
- /** Casts for selected columns, as if the model declared them: withCasts({ orders_sum_price: 'float' }). */
1587
- withCasts(casts: Readonly<Record<string, CastDefinition>>): this;
1488
+ static observe(...observers: Array<object | (new () => object)>): void;
1588
1489
  /**
1589
- * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').
1590
- * Uses `exists (…)` for the common "at least one"/"none" cases and a count subquery otherwise.
1490
+ * Turns the relation guard on or off: while it is on, reading a property of a relation method as if it were the
1491
+ * related model (`post.author.name`) warns once with how to read the relation. DatabaseServiceProvider turns it on
1492
+ * outside production. Turning it on again forgets which warnings were given.
1591
1493
  */
1592
- has(relation: string, operator?: string, count?: number, boolean?: 'and' | 'or', callback?: RelationConstraint): this;
1593
- orHas(relation: string, operator?: string, count?: number): this;
1594
- doesntHave(relation: string, boolean?: 'and' | 'or', callback?: RelationConstraint): this;
1595
- orDoesntHave(relation: string): this;
1596
- /** Rows with related rows matching the callback: whereHas('comments', (q) => q.where('approved', true)). */
1597
- whereHas(relation: string, callback?: RelationConstraint, operator?: string, count?: number): this;
1598
- orWhereHas(relation: string, callback?: RelationConstraint, operator?: string, count?: number): this;
1599
- whereDoesntHave(relation: string, callback?: RelationConstraint): this;
1600
- orWhereDoesntHave(relation: string, callback?: RelationConstraint): this;
1601
- /** has('comments.author'): whereHas('comments', q => q.has('author')) */
1602
- private hasNested;
1603
- private normalizeRelationSpecs;
1604
- /** Models from raw rows, marked as existing. */
1605
- hydrate(rows: readonly Row[]): M[];
1606
- aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown>;
1607
- exists(): Promise<boolean>;
1608
- /** The column's values, through the model's casts and accessors. */
1609
- pluck<V = unknown>(column: Column<M>): Promise<Collection<V>>;
1610
- /** Whether `id` can't be one of the model's unique ids (not a UUID for HasUuids): it matches no row. */
1611
- protected isMalformedKey(id: unknown): boolean;
1612
- /** A malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. */
1613
- find(id: unknown): Promise<M | undefined>;
1614
- findMany(ids: readonly unknown[]): Promise<EloquentCollection<M>>;
1615
- /** find(), or ModelNotFoundError (a 404). With an array, every id must exist. */
1616
- findOrFail(ids: readonly unknown[]): Promise<EloquentCollection<M>>;
1617
- findOrFail(id: unknown): Promise<M>;
1618
- findOr<R>(id: unknown, callback: () => R | Promise<R>): Promise<M | R>;
1619
- firstOrFail(): Promise<M>;
1620
- firstOr<R>(callback: () => R | Promise<R>): Promise<M | R>;
1621
- firstWhere(column: Column<M> | Expression, operatorOrValue: unknown, value?: unknown): Promise<M | undefined>;
1622
- /** A new, unsaved model of this query's class (mass assignment rules apply). */
1623
- newModelInstance(attributes?: Row): M;
1624
- make(attributes?: Row): M;
1625
- create(attributes?: Row): Promise<M>;
1626
- /** Creates without mass assignment protection. Never pass it request input. */
1627
- forceCreate(attributes: Row): Promise<M>;
1628
- /** The first match, or a new unsaved model with attributes + values. */
1629
- firstOrNew(attributes: Row, values?: Row): Promise<M>;
1630
- /** The first match, or a new saved model. A concurrent insert of the same unique key returns that row instead. */
1631
- firstOrCreate(attributes: Row, values?: Row): Promise<M>;
1632
- /** Tries to create; on a unique constraint violation, returns the existing row (Laravel's createOrFirst()). */
1633
- createOrFirst(attributes: Row, values?: Row): Promise<M>;
1634
- /** Updates the first match with values, or creates it. */
1635
- updateOrCreate(attributes: Row, values?: Row): Promise<M>;
1636
- /** Mass update (no model events); sets updated_at when the model uses timestamps. */
1637
- update(values: Row): Promise<number>;
1638
- /** Mass delete (no model events). With soft deletes this sets deleted_at on the matching rows instead. */
1639
- delete(): Promise<number>;
1640
- /** Deletes the matching rows for real, even with soft deletes. */
1641
- forceDelete(): Promise<number>;
1642
- /** Includes soft-deleted rows (withTrashed(false) is withoutTrashed()). */
1643
- withTrashed(withTrashed?: boolean): this;
1644
- /** Excludes soft-deleted rows explicitly. */
1645
- withoutTrashed(): this;
1646
- /** Only soft-deleted rows. */
1647
- onlyTrashed(): this;
1648
- /** Restores every matching row (deleted_at = null), trashed or not. */
1649
- restore(): Promise<number>;
1650
- protected addUpdatedAtColumn(values: Row): Row;
1651
- toSql(): string;
1652
- getBindings(): unknown[];
1653
- clone(): Builder<M>;
1654
- /** Nested where groups get a builder of the same model (without global scopes), so local scopes work inside them. */
1655
- newQuery(): Builder$1<Row>;
1656
- /** chunk() and lazy() order by the primary key when the query has no order. */
1657
- protected enforceOrderBy(): void;
1658
- protected defaultKeyName(): string;
1659
- protected defaultPerPage(): number;
1660
- }
1661
-
1662
- declare const MANY: unique symbol;
1663
- /** Type-level marker set by count(): make()/create() then return a Collection. */
1664
- interface Many {
1665
- readonly [MANY]: true;
1666
- }
1667
- /** What make()/create() return: a model, or a Collection after count(). */
1668
- type FactoryResult<F, M> = F extends Many ? Collection<M> : M;
1669
- /** What raw() returns: the attributes, or a list of them after count(). */
1670
- type RawResult<F> = F extends Many ? Row[] : Row;
1671
- /** Which model a state is being made for: its index in count() and the total. */
1672
- interface StateContext {
1673
- index: number;
1674
- count: number;
1675
- }
1676
- type State = Row | ((attributes: Row, context: StateContext) => Row);
1677
- type AnyFactory = Factory<any>;
1678
- /**
1679
- * What has() and for() need from a factory: its model, create(), createOne() and state(). A factory of any model,
1680
- * counted or not, has them; Factory<any> itself would refuse a counted one, whose make(), create() and raw() return
1681
- * lists.
1682
- */
1683
- interface RelatedFactory {
1684
- readonly model: new () => Model;
1685
- create(attributes?: Row): Promise<unknown>;
1686
- createOne(attributes?: Row): Promise<Model>;
1687
- state(state: State): RelatedFactory;
1688
- }
1689
- /**
1690
- * A model's factory() typed as its own factory class (Laravel's `@use HasFactory<UserFactory>`): declare it in the
1691
- * model, `declare static factory: HasFactory<UserFactory>` (with `import type`), and User.factory().unverified()
1692
- * type-checks. The factory is still found at run time by name (database/factories/UserFactory.ts).
1693
- */
1694
- type HasFactory<F> = {
1695
- (): F;
1696
- (count: number, state?: State): F & Many;
1697
- } & (typeof Model)['factory'];
1698
- interface HasRelationship {
1699
- factory: RelatedFactory;
1700
- relationship: string;
1701
- pivot: Row;
1702
- }
1703
- interface ForRelationship {
1704
- parent: RelatedFactory | Model;
1705
- relationship: string;
1706
- resolved?: Model;
1707
- }
1708
- /** The builder state newInstance() copies and changes. */
1709
- interface FactoryState<M extends Model> {
1710
- countValue: number | undefined;
1711
- states: State[];
1712
- hasRelations: HasRelationship[];
1713
- forRelations: ForRelationship[];
1714
- afterMakingCallbacks: Array<(model: M) => unknown>;
1715
- afterCreatingCallbacks: Array<(model: M) => unknown>;
1716
- }
1717
- /**
1718
- * Laravel's model factories: `class UserFactory extends Factory<User> { model = User; definition() { … } }`,
1719
- * then `await User.factory().count(3).create()`, `UserFactory.new().unverified().make()`.
1720
- * Every builder method returns a new factory, so a base factory can be reused.
1721
- */
1722
- declare abstract class Factory<M extends Model = Model> {
1723
- /** The model class this factory makes. */
1724
- abstract model: new () => M;
1725
- /** The default attributes. Values may be factories (created for their key) or (attributes) => value functions. */
1726
- abstract definition(): Row;
1727
- protected countValue: number | undefined;
1728
- protected states: State[];
1729
- protected hasRelations: HasRelationship[];
1730
- protected forRelations: ForRelationship[];
1731
- protected afterMakingCallbacks: Array<(model: M) => unknown>;
1732
- protected afterCreatingCallbacks: Array<(model: M) => unknown>;
1733
- /** A new factory with the given state (Laravel's Factory::new()). */
1734
- static new<F extends AnyFactory>(this: new () => F, state?: State): F;
1735
- /** Registers factory classes for Model.factory() (discoverFactories() does this for database/factories). */
1736
- static register(...factories: Array<new () => AnyFactory>): void;
1737
- /** The registered factory for a model class. */
1738
- static forModel<M extends Model>(model: new () => M): Factory<M>;
1739
- /** Hook for afterMaking()/afterCreating() registrations; runs in new(). */
1740
- configure(): this;
1741
- /** How many models make()/create() produce; they then return a Collection. */
1742
- count(count: number): this & Many;
1743
- /** Overrides attributes: state({ admin: true }) or state((attributes) => ({ … })). */
1744
- state(state: State): this;
1745
- /** Cycles through states per model: sequence({ role: 'admin' }, { role: 'user' }). */
1746
- sequence(...states: State[]): this;
1747
- /** deleted_at = now, for soft-deleting models. */
1748
- trashed(): this;
1749
- /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */
1750
- has(factory: RelatedFactory, relationship?: string, pivot?: Row): this;
1751
- /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */
1752
- for(parent: RelatedFactory | Model, relationship?: string): this;
1753
- afterMaking(callback: (model: M) => unknown): this;
1754
- afterCreating(callback: (model: M) => unknown): this;
1755
- /** The attributes only, without a model (a Row, or a Row[] after count()). */
1756
- raw(attributes?: Row): Promise<RawResult<this>>;
1757
- /** Unsaved models (afterMaking callbacks run). */
1758
- make(attributes?: Row): Promise<FactoryResult<this, M>>;
1759
- /** Saved models, with their has() relations (afterCreating callbacks run). */
1760
- create(attributes?: Row): Promise<FactoryResult<this, M>>;
1761
- makeOne(attributes?: Row): Promise<M>;
1762
- createOne(attributes?: Row): Promise<M>;
1763
- /** One model per record (or `count` models). */
1764
- createMany(records: number | Row[]): Promise<Collection<M>>;
1765
- protected newInstance(changes: Partial<FactoryState<M>>): this;
1766
- protected makeModels(attributes: Row): Promise<M[]>;
1767
- /** definition() + states + overrides + for() parents, with factory and function values expanded. */
1768
- protected attributesFor(overrides: Row, index: number): Promise<Row>;
1769
- private parentAttributes;
1770
- private createChildren;
1771
- private relationOn;
1772
- private result;
1773
- }
1774
- /** Imports every factory file in a directory and registers its exported Factory classes. */
1775
- declare function discoverFactories(path: string): Promise<void>;
1776
-
1777
- /** Laravel's model events. The -ing events of save, delete and restore can cancel by returning false. */
1778
- declare const MODEL_EVENTS: readonly ["retrieved", "creating", "created", "updating", "updated", "saving", "saved", "deleting", "deleted", "restoring", "restored", "forceDeleting", "forceDeleted"];
1779
- type ModelEvent = (typeof MODEL_EVENTS)[number];
1780
- /** A listener receives the model. Returning false from a halting event cancels the operation. */
1781
- type ModelListener<M> = (model: M) => unknown;
1782
- /** 'eloquent.created: Post' (Laravel uses the fully qualified class name; Oriel uses the class name). */
1783
- declare function modelEventName(event: string, className: string): string;
1784
-
1785
- /** post.author(): this model (the child) holds the related model's key. */
1786
- declare class BelongsTo<R extends Model, P extends Model = Model> extends Relation<R, P, R | null> {
1787
- readonly foreignKey: string;
1788
- readonly ownerKey: string;
1494
+ static warnOnRelationPropertyAccess(enabled?: boolean): void;
1495
+ static warnsOnRelationPropertyAccess(): boolean;
1496
+ /** Runs fn with model events off, for this async context only. */
1497
+ static withoutEvents<R>(fn: () => R): R;
1498
+ /** A new query of this model, with its global scopes. */
1499
+ static query<C extends typeof Model>(this: C): ModelBuilder<C>;
1500
+ static where<C extends typeof Model>(this: C, ...args: WhereArgs<Instance<C>, ModelBuilder<C>>): ModelBuilder<C>;
1501
+ /** Post.when(request.query('q'), (query, q) => query.whereLike('title', `%${q}%`)): a new query, then when(). */
1502
+ static when<C extends typeof Model, V>(this: C, value: (query: ModelBuilder<C>) => V, callback: (query: ModelBuilder<C>, value: Truthy<V>) => unknown, otherwise?: (query: ModelBuilder<C>, value: V) => unknown): ModelBuilder<C>;
1503
+ static when<C extends typeof Model, V>(this: C, value: V, callback: (query: ModelBuilder<C>, value: Truthy<V>) => unknown, otherwise?: (query: ModelBuilder<C>, value: V) => unknown): ModelBuilder<C>;
1504
+ /** A new query, then unless(): the callback runs when the value is falsy. */
1505
+ static unless<C extends typeof Model, V>(this: C, value: (query: ModelBuilder<C>) => V, callback: (query: ModelBuilder<C>, value: V) => unknown, otherwise?: (query: ModelBuilder<C>, value: Truthy<V>) => unknown): ModelBuilder<C>;
1506
+ static unless<C extends typeof Model, V>(this: C, value: V, callback: (query: ModelBuilder<C>, value: V) => unknown, otherwise?: (query: ModelBuilder<C>, value: Truthy<V>) => unknown): ModelBuilder<C>;
1507
+ static whereKey<C extends typeof Model>(this: C, id: unknown): ModelBuilder<C>;
1508
+ static whereIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C>;
1509
+ static whereNotIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C>;
1510
+ static whereNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C>;
1511
+ static whereNotNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C>;
1512
+ static whereBetween<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly [unknown, unknown]): ModelBuilder<C>;
1513
+ /** Post.whereLike('title', `%${term}%`): case-insensitive unless caseSensitive (see the query builder's whereLike()). */
1514
+ static whereLike<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, value: string, caseSensitive?: boolean): ModelBuilder<C>;
1515
+ static whereNotLike<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, value: string, caseSensitive?: boolean): ModelBuilder<C>;
1516
+ /** Post.whereDate('published_at', '2026-01-05'), Post.whereDate('published_at', '<', new Date()). */
1517
+ static whereDate<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
1518
+ static whereTime<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
1519
+ static whereDay<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
1520
+ static whereMonth<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
1521
+ static whereYear<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
1522
+ static whereColumn<C extends typeof Model>(this: C, first: Column<Instance<C>>, operatorOrSecond: string, second?: Column<Instance<C>>): ModelBuilder<C>;
1523
+ static whereRaw<C extends typeof Model>(this: C, sql: string, bindings?: readonly unknown[]): ModelBuilder<C>;
1524
+ static select<C extends typeof Model>(this: C, ...columns: Array<Column<Instance<C>> | Expression>): ModelBuilder<C>;
1525
+ static orderBy<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, direction?: Direction): ModelBuilder<C>;
1526
+ static latest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C>;
1527
+ static oldest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C>;
1528
+ static inRandomOrder<C extends typeof Model>(this: C): ModelBuilder<C>;
1529
+ static limit<C extends typeof Model>(this: C, count: number): ModelBuilder<C>;
1530
+ static take<C extends typeof Model>(this: C, count: number): ModelBuilder<C>;
1531
+ static withoutGlobalScope<C extends typeof Model>(this: C, scope: string | ScopeClass): ModelBuilder<C>;
1532
+ static withoutGlobalScopes<C extends typeof Model>(this: C, scopes?: Array<string | ScopeClass>): ModelBuilder<C>;
1533
+ /** Eager loads relations: Post.with('author', 'comments.user').get(). */
1534
+ static with<C extends typeof Model, const S extends readonly LooseSpec[]>(this: C, ...relations: EagerLoads<Instance<C>, S>): ModelBuilder<C, WithLoaded<Instance<C>, LoadedTree<S>>> & ModelBuilder<C>;
1535
+ static withCount<C extends typeof Model, const S extends readonly LooseSpec[]>(this: C, ...relations: Aggregates<Instance<C>, S>): ModelBuilder<C>;
1536
+ /** Post.withSum('orders', 'price'): adds orders_sum_price. */
1537
+ static withSum<C extends typeof Model, const S extends LooseSpec | readonly LooseSpec[]>(this: C, relations: AggregateSpecs<Instance<C>, S>, column: string | Expression): ModelBuilder<C>;
1538
+ static withAvg<C extends typeof Model, const S extends LooseSpec | readonly LooseSpec[]>(this: C, relations: AggregateSpecs<Instance<C>, S>, column: string | Expression): ModelBuilder<C>;
1539
+ static withMin<C extends typeof Model, const S extends LooseSpec | readonly LooseSpec[]>(this: C, relations: AggregateSpecs<Instance<C>, S>, column: string | Expression): ModelBuilder<C>;
1540
+ static withMax<C extends typeof Model, const S extends LooseSpec | readonly LooseSpec[]>(this: C, relations: AggregateSpecs<Instance<C>, S>, column: string | Expression): ModelBuilder<C>;
1541
+ static withExists<C extends typeof Model, const S extends readonly LooseSpec[]>(this: C, ...relations: Aggregates<Instance<C>, S>): ModelBuilder<C>;
1542
+ static withAggregate<C extends typeof Model, const S extends LooseSpec | readonly LooseSpec[]>(this: C, relations: AggregateSpecs<Instance<C>, S>, column: string | Expression, fn?: string): ModelBuilder<C>;
1543
+ static has<C extends typeof Model, const N extends RelationPath<Instance<C>> | (string & {})>(this: C, relation: RelationPathArg<Instance<C>, N>, operator?: string, count?: number): ModelBuilder<C>;
1544
+ static whereHas<C extends typeof Model, const N extends RelationPath<Instance<C>> | (string & {})>(this: C, relation: RelationPathArg<Instance<C>, N>, callback?: RelationConstraint, operator?: string, count?: number): ModelBuilder<C>;
1545
+ static doesntHave<C extends typeof Model, const N extends RelationPath<Instance<C>> | (string & {})>(this: C, relation: RelationPathArg<Instance<C>, N>): ModelBuilder<C>;
1546
+ static whereDoesntHave<C extends typeof Model, const N extends RelationPath<Instance<C>> | (string & {})>(this: C, relation: RelationPathArg<Instance<C>, N>, callback?: RelationConstraint): ModelBuilder<C>;
1547
+ /** Soft deletes: include trashed rows. */
1548
+ static withTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
1549
+ /** Soft deletes: only trashed rows. */
1550
+ static onlyTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
1551
+ static withoutTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
1552
+ static all<C extends typeof Model>(this: C): Promise<EloquentCollection<Instance<C>>>;
1553
+ static find<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>;
1554
+ static find<C extends typeof Model>(this: C, id: ModelKey | null | undefined): Promise<Instance<C> | undefined>;
1555
+ /** A key typed `unknown` may be an array at run time (`?id[]=1`): a model or a collection. */
1556
+ static find<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | EloquentCollection<Instance<C>> | undefined>;
1557
+ static findOrFail<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>;
1558
+ static findOrFail<C extends typeof Model>(this: C, id: ModelKey | null | undefined): Promise<Instance<C>>;
1559
+ static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | EloquentCollection<Instance<C>>>;
1560
+ static findMany<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>;
1561
+ static first<C extends typeof Model>(this: C): Promise<Instance<C> | undefined>;
1562
+ static firstOrFail<C extends typeof Model>(this: C): Promise<Instance<C>>;
1563
+ static firstWhere<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, operatorOrValue: unknown, value?: unknown): Promise<Instance<C> | undefined>;
1564
+ static count(): Promise<number>;
1565
+ static exists(): Promise<boolean>;
1566
+ static pluck<C extends typeof Model, V = unknown>(this: C, column: Column<Instance<C>>): Promise<Collection<V>>;
1567
+ static paginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<LengthAwarePaginator<Instance<C>>>;
1568
+ static simplePaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<Paginator<Instance<C>>>;
1569
+ static cursorPaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], cursorName?: string, cursor?: Cursor | string): Promise<CursorPaginator<Instance<C>>>;
1570
+ static chunk<C extends typeof Model>(this: C, count: number, callback: (models: EloquentCollection<Instance<C>>, page: number) => unknown): Promise<boolean>;
1571
+ static chunkById<C extends typeof Model>(this: C, count: number, callback: (models: EloquentCollection<Instance<C>>, page: number) => unknown): Promise<boolean>;
1572
+ static each<C extends typeof Model>(this: C, callback: (model: Instance<C>, index: number) => unknown, count?: number): Promise<boolean>;
1573
+ static lazy<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>>;
1574
+ static lazyById<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>>;
1575
+ /** Creates and saves a model (mass assignment rules apply). */
1576
+ static create<C extends typeof Model, const T extends object = Row>(this: C, attributes?: T & WriteAttributes<Instance<C>, T>): Promise<Instance<C>>;
1577
+ static forceCreate<C extends typeof Model, const T extends object = Row>(this: C, attributes: T & WriteAttributes<Instance<C>, T>): Promise<Instance<C>>;
1578
+ static firstOrNew<C extends typeof Model, const A extends object = Row, const V extends object = Row>(this: C, attributes: A & WriteAttributes<Instance<C>, A>, values?: V & WriteAttributes<Instance<C>, V>): Promise<Instance<C>>;
1579
+ static firstOrCreate<C extends typeof Model, const A extends object = Row, const V extends object = Row>(this: C, attributes: A & WriteAttributes<Instance<C>, A>, values?: V & WriteAttributes<Instance<C>, V>): Promise<Instance<C>>;
1580
+ static updateOrCreate<C extends typeof Model, const A extends object = Row, const V extends object = Row>(this: C, attributes: A & WriteAttributes<Instance<C>, A>, values?: V & WriteAttributes<Instance<C>, V>): Promise<Instance<C>>;
1581
+ /**
1582
+ * The model's registered factory (database/factories/<Model>Factory.ts): await User.factory().create(),
1583
+ * await User.factory(3).create(). Use UserFactory.new() to reach the factory's own state methods with their types.
1584
+ */
1585
+ static factory<C extends typeof Model>(this: C): Factory<InstanceType<C>>;
1586
+ static factory<C extends typeof Model>(this: C, count: number, state?: State): Factory<InstanceType<C>> & Many;
1587
+ /** Deletes models by key, one by one, so model events fire. Returns how many were deleted. */
1588
+ static destroy(...ids: Array<unknown | unknown[]>): Promise<number>;
1589
+ /** Disables mass assignment protection everywhere until reguard(). */
1590
+ static unguard(state?: boolean): void;
1591
+ static reguard(): void;
1592
+ static isUnguarded(): boolean;
1593
+ /** Runs fn with mass assignment protection off, for this async context only (seeders, factories). */
1594
+ static unguarded<R>(fn: () => R): R;
1595
+ /** Sets the fillable attributes; the others are dropped, or throw MassAssignmentError on a totally guarded model. */
1596
+ fill<Self extends Model, const T extends object = Row, Concrete extends Model = Model>(this: Self & {
1597
+ readonly $self?: Concrete;
1598
+ }, attributes: T & WriteAttributes<Concrete, T>): this;
1599
+ /** Sets attributes with no mass assignment check. Never pass it request input. */
1600
+ forceFill<Self extends Model, const T extends object = Row, Concrete extends Model = Model>(this: Self & {
1601
+ readonly $self?: Concrete;
1602
+ }, attributes: T & WriteAttributes<Concrete, T>): this;
1603
+ isFillable(key: string): boolean;
1604
+ /** Guarded names match case-insensitively: SQLite and MySQL column names are case-insensitive. */
1605
+ isGuarded(key: string): boolean;
1606
+ totallyGuarded(): boolean;
1607
+ getFillable(): string[];
1608
+ getGuarded(): string[];
1609
+ /** An attribute through its accessor or cast; undefined when the model doesn't have it. */
1610
+ getAttribute<T = unknown>(key: string): T;
1611
+ /** The attribute's value after its accessor (get<Name>Attribute) or cast. */
1612
+ getAttributeValue(key: string): unknown;
1613
+ /** Sets an attribute through its mutator (set<Name>Attribute) or cast. */
1614
+ setAttribute(key: string, value: unknown): this;
1615
+ hasGetMutator(key: string): boolean;
1616
+ hasSetMutator(key: string): boolean;
1617
+ /** Every cast, including the implied ones: the incrementing key (int) and the timestamp columns (datetime). */
1618
+ getCasts(): Record<string, CastDefinition>;
1619
+ /** Adds casts to this instance only (Laravel's mergeCasts()); withCasts() on a query does it for each result. */
1620
+ mergeCasts(casts: Readonly<Record<string, CastDefinition>>): this;
1621
+ hasCast(key: string, types?: string[]): boolean;
1622
+ /** The stored attributes, with in-place changes to json casts written back. */
1623
+ getAttributes(): Row;
1624
+ /** Replaces the stored attributes as-is (no casts or mutators); sync = also make them the original. */
1625
+ setRawAttributes(attributes: Row, sync?: boolean): this;
1626
+ /** The original value (cast), or every original value. */
1627
+ getOriginal(): Row;
1628
+ getOriginal<T = unknown>(key: string): T;
1629
+ getRawOriginal(): Row;
1630
+ getRawOriginal<T = unknown>(key: string): T;
1631
+ syncOriginal(): this;
1632
+ syncOriginalAttributes(...keys: string[]): this;
1633
+ /** The attributes that changed since the model was loaded or saved, compared by meaning (casts), not representation. */
1634
+ getDirty(): Row;
1635
+ isDirty(...keys: Array<string | string[]>): boolean;
1636
+ isClean(...keys: Array<string | string[]>): boolean;
1637
+ /** The attributes the last save() changed. */
1638
+ getChanges(): Row;
1639
+ wasChanged(...keys: Array<string | string[]>): boolean;
1640
+ syncChanges(): this;
1641
+ /** The given attributes (through accessors and casts). */
1642
+ only(...keys: Array<string | string[]>): Row;
1643
+ /**
1644
+ * useCache = false skips the json-cast decode cache entirely (both reading and writing it): used by getOriginal(),
1645
+ * so a decoded original never aliases the live attribute's cached (and possibly in-place-mutated) object, even
1646
+ * when their raw stored strings are equal right after load/save.
1647
+ */
1648
+ protected castAttribute(key: string, value: unknown, useCache?: boolean): unknown;
1649
+ /** Writes json casts that were changed in place (post.meta.views++) back into the stored attributes. */
1650
+ protected mergeCachedCasts(): void;
1651
+ private mutatorFor;
1652
+ getKeyName(): string;
1653
+ getKeyType(): 'int' | 'string';
1654
+ getIncrementing(): boolean;
1655
+ /** Whether new rows get unique string ids before `creating` (HasUuids, HasUlids). */
1656
+ usesUniqueIds(): boolean;
1657
+ /** The columns that get a unique id (HasUuids and HasUlids: the primary key). */
1658
+ uniqueIds(): string[];
1659
+ /** A new unique id (HasUuids: a version 7 UUID; HasUlids: a lower-case ULID). */
1660
+ newUniqueId(): string | undefined;
1661
+ /** Whether a value has the shape of this model's unique ids (HasUuids: a UUID). Any value passes by default. */
1662
+ isValidUniqueId(_value: unknown): boolean;
1663
+ /** Fills each empty unique id column with newUniqueId() (Laravel's setUniqueIds()). */
1664
+ setUniqueIds(): void;
1665
+ /** The primary key's value: a string, a number or a bigint, or nothing on a model not yet saved. */
1666
+ getKey(): ModelKey | null | undefined;
1667
+ getTable(): string;
1668
+ getConnectionName(): string | undefined;
1669
+ getPerPage(): number;
1670
+ /** 'posts.title' for 'title'. Already-qualified columns are returned as-is. */
1671
+ qualifyColumn(column: string): string;
1672
+ getQualifiedKeyName(): string;
1673
+ /** The conventional foreign key pointing at this model: user_id for User. */
1674
+ getForeignKey(): string;
1675
+ getRouteKeyName(): string;
1676
+ getRouteKey(): unknown;
1677
+ /**
1678
+ * The model a route parameter value points at: where <field or route key> = value (global scopes apply, so a
1679
+ * soft-deleted row isn't found). A non-numeric value for an integer primary key, or a value that isn't a UUID
1680
+ * (ULID) for a unique id column, finds nothing without a query.
1681
+ */
1682
+ resolveRouteBinding(value: string, field?: string): Promise<this | undefined>;
1683
+ /** Override to customize the binding query (Laravel's resolveRouteBindingQuery()). */
1684
+ resolveRouteBindingQuery(query: Builder$1<this>, value: string, field: string): Builder$1<this>;
1685
+ usesTimestamps(): boolean;
1686
+ usesSoftDeletes(): boolean;
1687
+ getCreatedAtColumn(): string | null;
1688
+ getUpdatedAtColumn(): string | null;
1689
+ getDeletedAtColumn(): string;
1690
+ /** The model's database connection, from the DatabaseManager binding. */
1691
+ getConnection(): Connection;
1692
+ setConnection(name: string | undefined): this;
1693
+ setTable(table: string): this;
1694
+ /** A new instance of the same class, connection and table (mass assignment rules apply to attributes). */
1695
+ newInstance(attributes?: Row, exists?: boolean): this;
1696
+ /** An existing model from a database row (no casts or mutators applied to the row). */
1697
+ newFromBuilder(attributes: Row): this;
1698
+ /** A query of this model with its global scopes and default eager loads. */
1699
+ newQuery(): Builder$1<this>;
1700
+ /** A query with the default eager loads (`with`, `withCount`) but no global scopes. */
1701
+ newQueryWithoutScopes(): Builder$1<this>;
1702
+ /** A query with the global scopes but no default eager loads. */
1703
+ newQueryWithoutRelationships(): Builder$1<this>;
1704
+ /** Adds this class's global scopes to a builder (relations use it for the related model's scopes). */
1705
+ registerGlobalScopes<B extends Builder$1<Model>>(builder: B): B;
1789
1706
  /**
1790
- * @param foreignKey the column on the child ('user_id')
1791
- * @param ownerKey the key on the related model it points at ('id')
1707
+ * Adds this class's default `with` and `withCount` to a builder (relations use it for the related model's
1708
+ * defaults). A default count that reaches the same class again while it is being added (a self-referencing
1709
+ * relation, or two models counting each other) is skipped there instead of recursing forever.
1792
1710
  */
1793
- constructor(related: R, child: P, foreignKey: string, ownerKey: string, relationName?: string);
1794
- getChild(): P;
1795
- getForeignKeyName(): string;
1796
- getQualifiedForeignKeyName(): string;
1797
- getOwnerKeyName(): string;
1798
- getQualifiedOwnerKeyName(): string;
1799
- addConstraints(): void;
1800
- addEagerConstraints(models: P[]): void;
1801
- getResults(): Promise<R | null>;
1802
- initRelation(models: P[], relation: string): P[];
1803
- match(models: P[], results: R[], relation: string): P[];
1804
- /** Points the child at `model` (sets the foreign key and the loaded relation). Save the child afterwards. */
1805
- associate(model: R | null): P;
1806
- /** Clears the foreign key. Save the child afterwards. */
1807
- dissociate(): P;
1808
- getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1809
- /** The loaded-relation name: the resolved name, else the related class in camelCase (author → pass it explicitly). */
1810
- private relationKey;
1811
- }
1812
-
1813
- /** attach()/sync() accept ids, models, or { id: pivotAttributes }. */
1814
- type PivotIds = unknown | readonly unknown[] | Record<string, Row>;
1815
- interface SyncChanges {
1816
- attached: unknown[];
1817
- detached: unknown[];
1818
- updated: unknown[];
1819
- }
1820
- /**
1821
- * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).
1822
- * Each related model carries its pivot row as `tag.pivot` (withPivot() adds columns, withTimestamps() the timestamps).
1823
- */
1824
- declare class BelongsToMany<R extends Model, P extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {
1825
- readonly table: string;
1826
- readonly foreignPivotKey: string;
1827
- readonly relatedPivotKey: string;
1828
- readonly parentKey: string;
1829
- readonly relatedKey: string;
1830
- protected pivotColumns: string[];
1831
- protected pivotTimestamps: [string, string] | undefined;
1832
- constructor(related: R, parent: P, table: string, foreignPivotKey: string, relatedPivotKey: string, parentKey: string, relatedKey: string);
1833
- qualifyPivotColumn(column: string): string;
1834
- getTable(): string;
1835
- getForeignPivotKeyName(): string;
1836
- getRelatedPivotKeyName(): string;
1837
- getParentKey(): unknown;
1838
- addConstraints(): void;
1839
- addEagerConstraints(models: P[]): void;
1840
- /** Extra pivot columns to load onto tag.pivot. */
1841
- withPivot(...columns: Array<string | string[]>): this;
1842
- /** The pivot table has created_at/updated_at: they are set on attach() and loaded onto tag.pivot. */
1843
- withTimestamps(createdAt?: string, updatedAt?: string): this;
1844
- wherePivot(column: string, operator: unknown, value?: unknown): this;
1845
- wherePivotIn(column: string, values: readonly unknown[]): this;
1846
- /** Selects the related columns plus the pivot columns (as pivot_*), then moves those onto each model's pivot. */
1847
- runSelect(): Promise<R[]>;
1848
- getResults(): Promise<EloquentCollection<R>>;
1849
- initRelation(models: P[], relation: string): P[];
1850
- match(models: P[], results: R[], relation: string): P[];
1851
- getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1852
- /** Inserts pivot rows for ids (or models, or { id: attributes }), with shared extra attributes. */
1853
- attach(ids: PivotIds, attributes?: Row): Promise<void>;
1854
- /** Deletes pivot rows for ids, or every pivot row of the parent. Returns how many were deleted. */
1855
- detach(ids?: PivotIds): Promise<number>;
1856
- /** Makes the pivot rows exactly ids: attaches the missing ones, detaches the others, updates given attributes. */
1857
- sync(ids: PivotIds, detaching?: boolean): Promise<SyncChanges>;
1858
- syncWithoutDetaching(ids: PivotIds): Promise<SyncChanges>;
1859
- /** Attaches the ids that aren't attached and detaches the ones that are. */
1860
- toggle(ids: PivotIds): Promise<{
1861
- attached: unknown[];
1862
- detached: unknown[];
1863
- }>;
1864
- /** Updates the pivot row of one related id. Returns the number of affected rows. */
1865
- updateExistingPivot(id: unknown, attributes: Row): Promise<number>;
1866
- /** Saves a new related model and attaches it. */
1867
- create(attributes?: Row, pivotAttributes?: Row): Promise<R>;
1868
- /** Saves a related model and attaches it. */
1869
- save(model: R, pivotAttributes?: Row): Promise<R>;
1870
- /** A plain query builder on the pivot table. */
1871
- newPivotQuery(): Builder$1<Row>;
1872
- private currentPivotIds;
1873
- private pivotSelectColumns;
1874
- private hydratePivot;
1875
- private pivotRow;
1876
- /** ids → Map(id → extra pivot attributes). Models become their related key. */
1877
- private parseIds;
1878
- private idOf;
1879
- private isModel;
1880
- /** Object keys are strings; numeric ones go back to numbers for integer keys. */
1881
- private castKey;
1882
- }
1883
-
1884
- /** For morphOne/morphMany: the qualified type column and the parent's morph class stored in it. */
1885
- interface MorphConstraint {
1886
- type: string;
1887
- value: string;
1888
- }
1889
- /**
1890
- * The shared half of hasOne, hasMany, morphOne and morphMany: the related table holds the foreign key (and, for
1891
- * the morph relations, the parent's type).
1892
- */
1893
- declare abstract class HasOneOrMany<R extends Model, P extends Model, Result> extends Relation<R, P, Result> {
1894
- readonly foreignKey: string;
1895
- readonly localKey: string;
1896
- readonly morph?: MorphConstraint | undefined;
1897
- /** The relation on each related model that chaperone() points back at the parent. */
1898
- protected inverseRelationship: string | undefined;
1711
+ registerDefaultEagerLoads<B extends Builder$1<Model>>(builder: B): B;
1712
+ /** A bare builder for this model: no global scopes, no default eager loads. */
1713
+ newModelQuery(): Builder$1<this>;
1899
1714
  /**
1900
- * @param foreignKey the qualified foreign key on the related table ('comments.post_id')
1901
- * @param localKey the key on the parent it points at ('id')
1902
- * @param morph the type column and value, for morphOne/morphMany
1715
+ * Inserts the model, or updates its dirty attributes. Only changed columns are written; an unchanged model
1716
+ * runs no query at all. Returns false when a saving/creating/updating listener cancels.
1903
1717
  */
1904
- constructor(related: R, parent: P, foreignKey: string, localKey: string, morph?: MorphConstraint | undefined);
1905
- /** 'post_id' */
1906
- getForeignKeyName(): string;
1907
- getQualifiedForeignKeyName(): string;
1908
- getParentKey(): unknown;
1909
- getQualifiedParentKeyName(): string;
1910
- /** 'commentable_type' for a morph relation. */
1911
- getMorphType(): string | undefined;
1912
- /** The parent's value in the type column, for a morph relation. */
1913
- getMorphClass(): string | undefined;
1718
+ save(): Promise<boolean>;
1914
1719
  /**
1915
- * Laravel's chaperone(): every related model this relation loads, eagerly or lazily, or makes, gets the parent as
1916
- * its `relation` (guessed when not given: post_id → post, the parent's class, owner), so reading it needs no query:
1917
- * `comments() { return this.hasMany(Comment).chaperone() }`.
1720
+ * Laravel's hashed cast (castAttributeAsHashedString()), run when the model is saved because the Hasher is
1721
+ * asynchronous: each newly assigned value is hashed before the saving event, so every listener sees the hash, and
1722
+ * again just before the write (after the creating or updating event), so a value a listener assigns is hashed too.
1723
+ * A value that is already a hash is kept when it matches the configured algorithm and options, and refused
1724
+ * otherwise. Only strings and numbers are hashed (null stays null); any other value is refused.
1918
1725
  */
1919
- chaperone(relation?: string): this;
1920
- /** Laravel's inverse(): chaperone() under its other name. */
1921
- inverse(relation?: string): this;
1922
- withoutChaperone(): this;
1923
- withoutInverse(): this;
1924
- getInverseRelationship(): string | undefined;
1925
- /** The first of the possible names that is a relation of the related model. */
1926
- protected guessInverseRelation(): string | undefined;
1927
- /** Laravel's candidates: the morph name, the foreign key without the parent's key, the parent's class, owner, parent. */
1928
- protected getPossibleInverseRelations(): string[];
1929
- /** Sets the parent on a related model, when chaperone() named the relation. */
1930
- protected applyInverseRelationToModel<M extends R | null | undefined>(model: M, parent?: P): M;
1931
- protected applyInverseRelationToMany(models: R[], parent?: P): R[];
1932
- /** The relation query's rows (get(), first(), paginate(), …), pointing back at the parent with chaperone(). */
1933
- runSelect(): Promise<R[]>;
1934
- addConstraints(): void;
1935
- addEagerConstraints(models: P[]): void;
1936
- /** Related models grouped by their foreign key, as strings: bigint and integer keys compare equal. */
1937
- protected buildDictionary(results: R[]): Map<string, R[]>;
1938
- /** New related models get the parent's key (and type): post.comments().create({ body }) sets post_id. */
1939
- newModelInstance(attributes?: Row): R;
1940
- /** Sets the foreign key (and type) on an existing model and saves it. */
1941
- save(model: R): Promise<R>;
1942
- protected setForeignAttributes(model: R): R;
1943
- saveMany(models: Iterable<R>): Promise<R[]>;
1944
- createMany(records: Row[]): Promise<R[]>;
1945
- getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1946
- }
1947
-
1948
- /** post.comments(): many related rows hold the parent's key. */
1949
- declare class HasMany<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, EloquentCollection<R>> {
1950
- getResults(): Promise<EloquentCollection<R>>;
1951
- initRelation(models: P[], relation: string): P[];
1952
- match(models: P[], results: R[], relation: string): P[];
1953
- }
1954
-
1955
- /**
1956
- * Related rows reached through an intermediate model: country.posts() → hasManyThrough(Post, User):
1957
- * posts join users on users.id = posts.user_id where users.country_id = countries.id.
1958
- */
1959
- declare class HasManyThrough<R extends Model, P extends Model = Model, T extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {
1960
- readonly throughParent: T;
1961
- readonly firstKey: string;
1962
- readonly secondKey: string;
1963
- readonly localKey: string;
1964
- readonly secondLocalKey: string;
1965
- /** The through key of each loaded model (kept off its attributes, so it never reaches toJSON()). */
1966
- private readonly throughKeys;
1726
+ protected hashPendingAttributes(): Promise<void>;
1727
+ /** Fills and saves an existing model. */
1728
+ update<Self extends Model, const T extends object = Row, Concrete extends Model = Model>(this: Self & {
1729
+ readonly $self?: Concrete;
1730
+ }, attributes?: T & WriteAttributes<Concrete, T>): Promise<boolean>;
1731
+ /**
1732
+ * Deletes the model's row, or sets deleted_at with soft deletes. Returns false for a model that isn't saved, or
1733
+ * when a deleting listener cancels.
1734
+ */
1735
+ delete(): Promise<boolean>;
1736
+ /** save() without model events. */
1737
+ saveQuietly(): Promise<boolean>;
1738
+ /** delete() without model events. */
1739
+ deleteQuietly(): Promise<boolean>;
1740
+ /** True when the model is soft deleted. Only for models with `softDeletes = true`. */
1741
+ trashed(): boolean;
1742
+ /** Clears deleted_at and saves. Fires restoring (can cancel) and restored. */
1743
+ restore(): Promise<boolean>;
1744
+ /** Deletes the row for real, even with soft deletes. Fires forceDeleting (can cancel) and forceDeleted. */
1745
+ forceDelete(): Promise<boolean>;
1746
+ isForceDeleting(): boolean;
1747
+ getQualifiedDeletedAtColumn(): string;
1748
+ private assertSoftDeletes;
1749
+ /** Reloads the attributes and the loaded relations from the database (including a soft-deleted row). */
1750
+ refresh(): Promise<this>;
1751
+ /** A fresh copy from the database, or undefined when the row is gone. */
1752
+ fresh(): Promise<this | undefined>;
1753
+ /** Updates updated_at (and saves). */
1754
+ touch(): Promise<boolean>;
1755
+ /** column = column + amount in the database, mirrored on the model without marking it dirty. */
1756
+ increment(column: string, amount?: number, extra?: Row): Promise<number>;
1757
+ decrement(column: string, amount?: number, extra?: Row): Promise<number>;
1758
+ /** Same table, connection and key. */
1759
+ is(other: Model | null | undefined): boolean;
1760
+ isNot(other: Model | null | undefined): boolean;
1761
+ /** The current time, to the second (the storage precision). */
1762
+ freshTimestamp(): Date;
1763
+ updateTimestamps(): void;
1764
+ protected performInsert(query: Builder$1<this>): Promise<boolean>;
1765
+ protected performUpdate(query: Builder$1<this>): Promise<boolean>;
1766
+ protected finishSave(): Promise<void>;
1767
+ protected performDeleteOnModel(): Promise<void>;
1768
+ /** deleted_at (and updated_at) = now, on this row only. The model still exists, as a trashed model. */
1769
+ protected runSoftDelete(): Promise<void>;
1770
+ /** where key = the key the row was loaded with (the original, in case the key itself changed). */
1771
+ protected setKeysForSaveQuery(query: Builder$1<this>): Builder$1<this>;
1772
+ protected incrementOrDecrement(column: string, amount: number, extra: Row): Promise<number>;
1773
+ /**
1774
+ * Dispatches 'eloquent.<event>: <Class>' with the model as payload. Halting events return false when a listener
1775
+ * returned false. A no-op without an EventDispatcher binding, or inside withoutEvents().
1776
+ */
1777
+ fireModelEvent(event: ModelEvent, halt?: boolean): Promise<boolean>;
1778
+ /** Whether any listener is registered for one of this model's events (retrieved is skipped when none is). */
1779
+ hasModelListeners(event: ModelEvent): boolean;
1780
+ /**
1781
+ * One related row holds this model's key: user.profile() → hasOne(Profile) (profiles.user_id = users.id).
1782
+ * @param foreignKey on the related table (default: this model's foreign key, e.g. user_id)
1783
+ * @param localKey on this model (default: the primary key)
1784
+ */
1785
+ hasOne<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasOne<InstanceType<C>, this> & Scopes<C>;
1786
+ /** Many related rows hold this model's key: post.comments() → hasMany(Comment) (comments.post_id = posts.id). */
1787
+ hasMany<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasMany<InstanceType<C>, this> & Scopes<C>;
1788
+ /**
1789
+ * This model holds the related model's key: post.author() → belongsTo(User, 'user_id').
1790
+ * @param foreignKey on this model (default: the related model's foreign key, e.g. user_id)
1791
+ * @param ownerKey on the related model (default: its primary key)
1792
+ * @param relation the loaded-relation name associate() sets (default: the resolved name, else the class in camelCase)
1793
+ */
1794
+ belongsTo<C extends typeof Model>(related: C, foreignKey?: string, ownerKey?: string, relation?: string): BelongsTo<InstanceType<C>, this> & Scopes<C>;
1795
+ /**
1796
+ * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).
1797
+ * @param table default: the two singular snake names in alphabetical order (post_tag)
1798
+ * @param foreignPivotKey the pivot column pointing at this model (default: post_id)
1799
+ * @param relatedPivotKey the pivot column pointing at the related model (default: tag_id)
1800
+ */
1801
+ belongsToMany<C extends typeof Model>(related: C, table?: string, foreignPivotKey?: string, relatedPivotKey?: string, parentKey?: string, relatedKey?: string): BelongsToMany<InstanceType<C>, this> & Scopes<C>;
1967
1802
  /**
1968
- * @param firstKey on the through table, pointing at the far parent ('users.country_id')
1969
- * @param secondKey on the related table, pointing at the through model ('posts.user_id')
1970
- * @param localKey on the far parent ('countries.id')
1971
- * @param secondLocalKey on the through model ('users.id')
1803
+ * Related rows through an intermediate model: country.posts() → hasManyThrough(Post, User).
1804
+ * @param firstKey on the through table (default: this model's foreign key, country_id)
1805
+ * @param secondKey on the related table (default: the through model's foreign key, user_id)
1972
1806
  */
1973
- constructor(related: R, farParent: P, throughParent: T, firstKey: string, secondKey: string, localKey: string, secondLocalKey: string);
1974
- /** users.country_id */
1975
- getQualifiedFirstKeyName(): string;
1976
- /** posts.user_id */
1977
- getQualifiedForeignKeyName(): string;
1978
- /** users.id */
1979
- getQualifiedParentKeyName(): string;
1980
- /** countries.id */
1981
- getQualifiedLocalKeyName(): string;
1982
- addConstraints(): void;
1983
- addEagerConstraints(models: P[]): void;
1984
- /** Selects the related columns plus the through key, then moves the key off the attributes. */
1985
- runSelect(): Promise<R[]>;
1986
- getResults(): Promise<EloquentCollection<R>>;
1987
- getEager(): Promise<EloquentCollection<R>>;
1988
- initRelation(models: P[], relation: string): P[];
1989
- match(models: P[], results: R[], relation: string): P[];
1990
- getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1991
- }
1992
-
1993
- /** user.profile(): one related row holds the parent's key. */
1994
- declare class HasOne<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, R | null> {
1995
- getResults(): Promise<R | null>;
1996
- initRelation(models: P[], relation: string): P[];
1997
- match(models: P[], results: R[], relation: string): P[];
1998
- }
1999
-
2000
- /** post.comments() → morphMany(Comment, 'commentable'): comments.commentable_id + commentable_type = 'Post'. */
2001
- declare class MorphMany<R extends Model, P extends Model = Model> extends HasMany<R, P> {
1807
+ hasManyThrough<C extends typeof Model, T extends typeof Model>(related: C, through: T, firstKey?: string, secondKey?: string, localKey?: string, secondLocalKey?: string): HasManyThrough<InstanceType<C>, this, InstanceType<T>> & Scopes<C>;
1808
+ /** A polymorphic one-to-one: user.image() → morphOne(Image, 'imageable') (images.imageable_id/_type). */
1809
+ morphOne<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphOne<InstanceType<C>, this> & Scopes<C>;
1810
+ /** A polymorphic one-to-many: post.comments() → morphMany(Comment, 'commentable'). */
1811
+ morphMany<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphMany<InstanceType<C>, this> & Scopes<C>;
2002
1812
  /**
2003
- * @param morphType the qualified type column ('comments.commentable_type')
2004
- * @param foreignKey the qualified id column ('comments.commentable_id')
1813
+ * The inverse of morphOne/morphMany: comment.commentable() → morphTo('commentable'). The name is required
1814
+ * (Laravel reads it from the calling method, which JavaScript can't do reliably).
2005
1815
  */
2006
- constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string);
2007
- }
2008
-
2009
- /** user.image() → morphOne(Image, 'imageable'): images.imageable_id + imageable_type = 'User'. */
2010
- declare class MorphOne<R extends Model, P extends Model = Model> extends HasOne<R, P> {
2011
- constructor(related: R, parent: P, morphType: string, foreignKey: string, localKey: string);
2012
- }
2013
-
2014
- /**
2015
- * comment.commentable() → morphTo('commentable'): the parent's class comes from commentable_type (a morph map alias
2016
- * or a class name) and its key from commentable_id. Eager loading runs one query per distinct type.
2017
- */
2018
- declare class MorphTo<R extends Model = Model, P extends Model = Model> extends BelongsTo<R, P> {
2019
- readonly morphTypeColumn: string;
2020
- readonly ownerKeyOverride: string | undefined;
2021
- /** Parents grouped by type, then by id, while eager loading. */
2022
- private dictionary;
2023
- /** The stored type each eager result was loaded for (an alias or a class name), for match(). */
2024
- private resultTypes;
1816
+ morphTo<R extends Model = Model>(name: string, type?: string, id?: string, ownerKey?: string): MorphTo<R, this>;
1817
+ /** The value stored in *_type columns for this model: its morph map alias, or its class name. */
1818
+ getMorphClass(): string;
1819
+ /** The pivot row of a model loaded through belongsToMany (tag.pivot.getAttribute('created_at')). */
1820
+ get pivot(): Model | undefined;
1821
+ /** A related model instance on this model's connection when it has none of its own. */
1822
+ protected newRelatedInstance<C extends typeof Model>(related: C): InstanceType<C>;
1823
+ /** Whether the model has a relation method called `name` (Laravel's isRelation()). */
1824
+ isRelation(name: string): boolean;
1825
+ /** Calls the relation method `name` (post.comments()) and checks that it returns a relation. */
1826
+ getRelationInstance(name: string): Relation;
2025
1827
  /**
2026
- * @param related an instance of the current type's class (the child's own class when the type is empty)
2027
- * @param morphType the type column on the child ('commentable_type')
2028
- * @param ownerKey the key on the parent (default: each class's primary key)
1828
+ * A loaded relation, typed from the relation method: post.getRelation('author') is User | null,
1829
+ * post.getRelation('comments') is EloquentCollection<Comment>. Throws RelationNotLoadedError when it isn't loaded
1830
+ * (JavaScript can't lazy-load synchronously: use with(), load() or post.comments().get()).
2029
1831
  */
2030
- constructor(related: R, child: P, foreignKey: string, morphTypeColumn: string, ownerKeyOverride: string | undefined, relationName: string);
2031
- getMorphType(): string;
2032
- addConstraints(): void;
2033
- getResults(): Promise<R | null>;
2034
- /** Groups the children by type and id; the queries run in getEager(). */
2035
- addEagerConstraints(models: P[]): void;
2036
- /** One query per type, with this relation's constraints and nested eager loads. */
2037
- getEager(): Promise<Collection<R>>;
2038
- match(models: P[], results: R[], relation: string): P[];
2039
- /** Points the child at `model`: sets the id and the type columns and the loaded relation. */
2040
- associate(model: R | null): P;
2041
- getRelationExistenceQuery(): Builder<R>;
1832
+ getRelation<K extends RelationNames<this>>(name: K): RelationValue<this, K>;
1833
+ /** Eager loads relations onto this model: await post.load('comments.author'). */
1834
+ load<Self extends Model, const S extends readonly LooseSpec[], Concrete extends Model = Model>(this: Self & {
1835
+ readonly $self?: Concrete;
1836
+ }, ...relations: EagerLoads<Concrete, S>): Promise<WithLoaded<Self, LoadedTree<S>>>;
1837
+ /** Loads only the relations that aren't loaded yet (nested paths are followed into loaded relations). */
1838
+ loadMissing<Self extends Model, const S extends readonly string[], Concrete extends Model = Model>(this: Self & {
1839
+ readonly $self?: Concrete;
1840
+ }, ...relations: EagerLoads<Concrete, S>): Promise<WithLoaded<Self, LoadedTree<S>>>;
1841
+ /** Loads <relation>_count attributes: await post.loadCount('comments'). */
1842
+ loadCount<Self extends Model, const S extends readonly LooseSpec[], Concrete extends Model = Model>(this: Self & {
1843
+ readonly $self?: Concrete;
1844
+ }, ...relations: Aggregates<Concrete, S>): Promise<Self>;
1845
+ /** Loads an aggregate of a relation as an attribute (Laravel's loadAggregate()): see withAggregate(). */
1846
+ loadAggregate<Self extends Model, const S extends LooseSpec | readonly LooseSpec[], Concrete extends Model = Model>(this: Self & {
1847
+ readonly $self?: Concrete;
1848
+ }, relations: AggregateSpecs<Concrete, S>, column: string | Expression, fn?: string): Promise<Self>;
1849
+ /** Loads <relation>_sum_<column>: await user.loadSum('orders', 'price'). */
1850
+ loadSum<Self extends Model, const S extends LooseSpec | readonly LooseSpec[], Concrete extends Model = Model>(this: Self & {
1851
+ readonly $self?: Concrete;
1852
+ }, relations: AggregateSpecs<Concrete, S>, column: string | Expression): Promise<Self>;
1853
+ loadAvg<Self extends Model, const S extends LooseSpec | readonly LooseSpec[], Concrete extends Model = Model>(this: Self & {
1854
+ readonly $self?: Concrete;
1855
+ }, relations: AggregateSpecs<Concrete, S>, column: string | Expression): Promise<Self>;
1856
+ loadMin<Self extends Model, const S extends LooseSpec | readonly LooseSpec[], Concrete extends Model = Model>(this: Self & {
1857
+ readonly $self?: Concrete;
1858
+ }, relations: AggregateSpecs<Concrete, S>, column: string | Expression): Promise<Self>;
1859
+ loadMax<Self extends Model, const S extends LooseSpec | readonly LooseSpec[], Concrete extends Model = Model>(this: Self & {
1860
+ readonly $self?: Concrete;
1861
+ }, relations: AggregateSpecs<Concrete, S>, column: string | Expression): Promise<Self>;
1862
+ /** Loads a boolean <relation>_exists. */
1863
+ loadExists<Self extends Model, const S extends readonly LooseSpec[], Concrete extends Model = Model>(this: Self & {
1864
+ readonly $self?: Concrete;
1865
+ }, ...relations: Aggregates<Concrete, S>): Promise<Self>;
1866
+ /**
1867
+ * The collection queries of this model return (Laravel's newCollection()): an EloquentCollection. Override it to
1868
+ * return a subclass with your own methods.
1869
+ */
1870
+ newCollection<T extends Model>(this: T, models?: T[]): EloquentCollection<T>;
1871
+ /** Stores a loaded relation (eager loading and load() use this). */
1872
+ setRelation(name: string, value: unknown): this;
1873
+ relationLoaded(name: string): boolean;
1874
+ unsetRelation(name: string): this;
1875
+ getRelations(): Record<string, unknown>;
1876
+ getHidden(): string[];
1877
+ setHidden(hidden: string[]): this;
1878
+ getVisible(): string[];
1879
+ setVisible(visible: string[]): this;
1880
+ /** Hides attributes for this instance only. */
1881
+ makeHidden(...attributes: Array<string | string[]>): this;
1882
+ /** Un-hides attributes for this instance only. */
1883
+ makeVisible(...attributes: Array<string | string[]>): this;
1884
+ getAppends(): string[];
1885
+ setAppends(appends: string[]): this;
1886
+ /** Adds accessor-only attributes to the serialized form of this instance. */
1887
+ append(...attributes: Array<string | string[]>): this;
1888
+ /**
1889
+ * Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones.
1890
+ * A model met again while its own toArray() runs (a child chaperone() pointed back at it) gives its attributes only.
1891
+ */
1892
+ toArray(): Row;
1893
+ toJSON(): Row;
1894
+ attributesToArray(): Row;
1895
+ /** Loaded relations under their snake_case names: a model → its array, a collection → an array of arrays. */
1896
+ relationsToArray(): Row;
1897
+ protected serializeValue(value: unknown): unknown;
1898
+ private isArrayableKey;
1899
+ private arrayable;
1900
+ }
1901
+ /** Eager loads relations onto models you already have (Laravel's $collection->load()). */
1902
+ declare function loadRelations<M extends Model>(models: Iterable<M>, ...relations: EagerLoadSpec[]): Promise<M[]>;
1903
+ /** A row of a belongsToMany pivot table, available as related.pivot (unguarded, no key, no timestamps by default). */
1904
+ declare class Pivot extends Model {
1905
+ protected guarded: string[];
1906
+ incrementing: boolean;
1907
+ timestamps: boolean;
2042
1908
  }
2043
1909
 
2044
- type Instance<C extends typeof Model> = InstanceType<C>;
2045
- type ScopeClass = abstract new (...args: never[]) => unknown;
2046
- /** Laravel's date serialization: ISO 8601 in UTC with microseconds (2026-01-02T03:04:05.000000Z). */
2047
- declare function serializeDate(date: Date): string;
1910
+ type AnyRelation = Relation<any, any, any>;
1911
+ /** A constraint on an eager load, withCount() or whereHas(): (query) => query.where(…). */
1912
+ type RelationConstraint = (query: AnyRelation) => unknown;
1913
+
1914
+ type AnyFunction = (...args: unknown[]) => unknown;
2048
1915
  /**
2049
- * Eloquent's Model: an Active Record over one table.
2050
- *
2051
- * Config lives in instance fields, as in Laravel: `protected fillable = ['title']`, `protected casts = {…}`,
2052
- * `protected hidden = ['password']`, `protected table = 'posts'`. Attribute columns are never declared as class
2053
- * fields (they would shadow the Proxy); their types come from `oriel model:types`, or from `declare title: string`.
2054
- * `new Post()` takes no arguments: use Post.make(attrs), Post.create(attrs) or new Post().fill(attrs).
1916
+ * Eloquent's builder: the query builder of one model class. Rows come back as hydrated models, global scopes are
1917
+ * applied when the query runs (grouped so an orWhere can't escape them), and unknown methods call the model's local
1918
+ * scopes. Everything the query builder does (pagination, chunk, lazy, …) returns models here.
2055
1919
  */
2056
- declare class Model implements ModelInstance {
2057
- static CREATED_AT: string | null;
2058
- static UPDATED_AT: string | null;
2059
- static DELETED_AT: string;
2060
- /** The table (default: the snake_case plural of the class name: BlogPost → blog_posts). */
2061
- protected table: string | undefined;
2062
- protected primaryKey: string;
2063
- protected keyType: 'int' | 'string';
2064
- incrementing: boolean;
2065
- /** Attributes that fill()/create() may set. */
2066
- protected fillable: string[];
2067
- /** Attributes fill() never sets. ['*'] (the default) guards everything that isn't fillable. */
2068
- protected guarded: string[];
2069
- protected casts: Readonly<Record<string, CastDefinition>>;
2070
- /** Left out of toArray()/toJSON(). */
2071
- protected hidden: string[];
2072
- /** When non-empty, only these are in toArray()/toJSON(). */
2073
- protected visible: string[];
2074
- /** Accessor-only attributes added to toArray()/toJSON(). */
2075
- protected appends: string[];
2076
- timestamps: boolean;
2077
- /** Turns on soft deletes (Laravel's `use SoftDeletes`): deleted_at instead of a real delete. */
2078
- protected softDeletes: boolean;
2079
- /** The connection name (default: config('database.default')). */
2080
- protected connection: string | undefined;
2081
- protected perPage: number;
2082
- /** Relations every query of this model eager loads (Laravel's $with). */
2083
- protected with: string[];
2084
- /** Relation counts every query of this model adds (Laravel's $withCount). */
2085
- protected withCount: string[];
2086
- exists: boolean;
2087
- wasRecentlyCreated: boolean;
2088
- protected forceDeleting: boolean;
2089
- protected attributes: Row;
2090
- protected original: Row;
2091
- protected changes: Row;
2092
- protected relations: Record<string, unknown>;
2093
- /** Decoded json/array/object/collection values, so in-place changes are seen by save(). */
2094
- protected castCache: Map<string, {
2095
- raw: unknown;
2096
- value: unknown;
2097
- }>;
2098
- /** Attributes with the hashed cast that were assigned a value since the last save; save() hashes them. */
2099
- protected pendingHashes: Set<string>;
2100
- constructor();
2101
- /** Runs booting()/booted() once per class, the first time the class is instantiated. */
2102
- static bootIfNotBooted(): void;
2103
- /**
2104
- * Framework hook: installs the static scope proxies (Post.published()) and, with `softDeletes = true`, the soft
2105
- * delete scope. Overrides must call super.boot().
2106
- */
2107
- static boot(): void;
2108
- /** Runs before boot(). */
2109
- static booting(): void;
2110
- /** Register global scopes and model event listeners here: static booted() { this.addGlobalScope(…) }. */
2111
- static booted(): void;
1920
+ declare class Builder$1<M extends Model = Model> extends Builder<M> {
1921
+ readonly model: M;
1922
+ protected scopes: Map<string, GlobalScope>;
1923
+ protected removedScopes: string[];
1924
+ protected eagerLoad: Map<string, RelationConstraint | undefined>;
1925
+ /** Casts for the selected columns (withCasts()), merged into every model this query hydrates. */
1926
+ protected selectCasts: Record<string, CastDefinition>;
1927
+ constructor(model: M);
1928
+ getModel(): M;
1929
+ /** The model class's static scope<Name> method for a builder method name, if any. */
1930
+ localScope(name: string): AnyFunction | undefined;
1931
+ /** Runs a scope; the wheres it adds are grouped when they contain an "or" (Laravel's callScope). */
1932
+ callScope(scope: (query: this) => unknown): this;
1933
+ withGlobalScope(name: string, scope: GlobalScope): this;
1934
+ /** Removes a global scope by name or Scope class. */
1935
+ withoutGlobalScope(scope: string | (abstract new (...args: never[]) => unknown)): this;
1936
+ /** Removes every global scope, or the given ones. */
1937
+ withoutGlobalScopes(scopes?: Array<string | (abstract new (...args: never[]) => unknown)>): this;
1938
+ removedScopeNames(): string[];
1939
+ /** A copy of this query with every global scope applied (Laravel's applyScopes()). */
1940
+ applyScopes(): this;
1941
+ /** Groups [0, count) and [count, …) separately when either contains an "or", so scopes combine with "and". */
1942
+ protected addNewWheresWithinGroup(count: number): void;
1943
+ private groupWhereSlice;
1944
+ where(column: Column<M> | Expression, value: unknown): this;
1945
+ where(column: Column<M> | Expression, operator: Operator | string, value: unknown): this;
1946
+ where(conditions: Row): this;
1947
+ where(callback: (query: this) => unknown): this;
1948
+ orWhere(column: Column<M> | Expression, value: unknown): this;
1949
+ orWhere(column: Column<M> | Expression, operator: Operator | string, value: unknown): this;
1950
+ orWhere(conditions: Row): this;
1951
+ orWhere(callback: (query: this) => unknown): this;
1952
+ whereIn(column: Column<M> | Expression, values: readonly unknown[] | Builder<unknown>): this;
1953
+ whereNotIn(column: Column<M> | Expression, values: readonly unknown[] | Builder<unknown>): this;
1954
+ whereNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this;
1955
+ whereNotNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this;
1956
+ whereBetween(column: Column<M> | Expression, values: readonly [unknown, unknown]): this;
1957
+ whereDate(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1958
+ orWhereDate(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1959
+ whereTime(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1960
+ orWhereTime(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1961
+ whereDay(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1962
+ orWhereDay(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1963
+ whereMonth(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1964
+ orWhereMonth(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1965
+ whereYear(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1966
+ orWhereYear(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1967
+ whereLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean, boolean?: WhereBoolean, not?: boolean): this;
1968
+ orWhereLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean): this;
1969
+ whereNotLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean, boolean?: WhereBoolean): this;
1970
+ orWhereNotLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean): this;
1971
+ orderBy(column: Column<M> | Expression, direction?: Direction | Uppercase<Direction>): this;
1972
+ /** Newest first by the model's created_at column (or the given one). */
1973
+ latest(column?: Column<M> | Expression): this;
1974
+ oldest(column?: Column<M> | Expression): this;
1975
+ select(...columns: Array<Column<M> | Expression | Array<Column<M> | Expression>>): this;
1976
+ /** where key = id (or key in ids). */
1977
+ whereKey(id: unknown): this;
1978
+ whereKeyNot(id: unknown): this;
1979
+ /** The models, in the model's collection (an EloquentCollection). */
1980
+ get(): Promise<EloquentCollection<M>>;
1981
+ protected newCollection(models: M[]): EloquentCollection<M>;
1982
+ /** chunk() with each chunk in the model's collection. */
1983
+ chunk(count: number, callback: (models: EloquentCollection<M>, page: number) => unknown): Promise<boolean>;
1984
+ chunkById(count: number, callback: (models: EloquentCollection<M>, page: number) => unknown, column?: string, alias?: string): Promise<boolean>;
1985
+ /** Runs the query, hydrates models, fires their retrieved events and eager loads the with() relations. */
1986
+ runSelect(): Promise<M[]>;
2112
1987
  /**
2113
- * Forgets which classes are booted, and their global scopes (Laravel's clearBootedModels()), so the next use boots
2114
- * them again: booted() re-registers its scopes and event listeners against the current application. Every new
2115
- * application does this (DatabaseServiceProvider.register()).
1988
+ * Relations to load with the results, one query per relation (and per nesting level):
1989
+ * with('author'), with('comments.author'), with({ comments: (q) => q.where('approved', true) }), with('author:id,name').
2116
1990
  */
2117
- static clearBootedModels(): void;
2118
- /** One cached instance per class, used by static methods to read config (table, key, casts, …). */
2119
- static prototypeInstance<M extends Model>(this: new () => M): M;
2120
- /** A new, unsaved model filled with attributes (mass assignment rules apply). */
2121
- static make<M extends Model>(this: new () => M, attributes?: Row): M;
1991
+ with<const S extends readonly LooseSpec[]>(...relations: EagerLoads<M, S>): LoadedBuilder<this, WithLoaded<M, LoadedTree<S>>>;
1992
+ with(this: Builder$1<UntypedModel>, ...relations: LooseSpec[]): this;
1993
+ /** Removes eager loads (including the model's default `with`). */
1994
+ without<const S extends readonly string[]>(...relations: S & {
1995
+ [I in keyof S]: RelationPathArg<M, S[I]>;
1996
+ }): this;
1997
+ without(this: Builder$1<UntypedModel>, ...relations: string[]): this;
1998
+ getEagerLoads(): Map<string, RelationConstraint | undefined>;
1999
+ /** Loads every top-level with() relation onto the models (nested ones are passed down to each relation query). */
2000
+ eagerLoadRelations(models: M[]): Promise<M[]>;
2001
+ /** The relation instance for a name, without its per-parent constraints. */
2002
+ getRelation(name: string): AnyRelation;
2003
+ protected eagerLoadRelation(models: M[], name: string, constraint: RelationConstraint | undefined): Promise<void>;
2004
+ private addEagerLoad;
2005
+ private relationsNestedUnder;
2122
2006
  /**
2123
- * Adds a global scope to every query of this class: addGlobalScope('published', q => …),
2124
- * addGlobalScope(new ActiveScope()) (named after its class) or addGlobalScope(q => …).
2007
+ * Adds `<relation>_count` columns: withCount('comments'), withCount({ comments: (q) => q.where('approved', true) }),
2008
+ * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.
2125
2009
  */
2126
- static addGlobalScope(scope: Scope | ScopeCallback): string;
2127
- static addGlobalScope(name: string, scope: GlobalScope): string;
2128
- static hasGlobalScope(scope: string | ScopeClass): boolean;
2129
- static getGlobalScopes(): Map<string, GlobalScope>;
2130
- /** Registers a listener for one of this model's events ('eloquent.<event>: <Class>'). Needs an EventDispatcher. */
2131
- static registerModelEvent<C extends typeof Model>(this: C, event: ModelEvent, callback: ModelListener<InstanceType<C>>): void;
2132
- static retrieved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2133
- static creating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2134
- static created<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2135
- static updating<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2136
- static updated<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2137
- static saving<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2138
- static saved<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2139
- static deleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2140
- static deleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2141
- static restoring<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2142
- static restored<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2143
- static forceDeleting<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2144
- static forceDeleted<C extends typeof Model>(this: C, callback: ModelListener<InstanceType<C>>): void;
2010
+ withCount<const S extends readonly LooseSpec[]>(...relations: Aggregates<M, S>): this;
2011
+ withCount(this: Builder$1<UntypedModel>, ...relations: LooseSpec[]): this;
2012
+ /** Adds `<relation>_sum_<column>`: withSum('orders', 'price'), withSum({ 'orders as paid': (q) => … }, 'price'). */
2013
+ withSum<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): this;
2014
+ withSum(this: Builder$1<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this;
2015
+ /** Adds `<relation>_avg_<column>`. */
2016
+ withAvg<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): this;
2017
+ withAvg(this: Builder$1<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this;
2018
+ /** Adds `<relation>_min_<column>`. */
2019
+ withMin<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): this;
2020
+ withMin(this: Builder$1<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this;
2021
+ /** Adds `<relation>_max_<column>`. */
2022
+ withMax<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): this;
2023
+ withMax(this: Builder$1<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): this;
2024
+ /** Adds a boolean `<relation>_exists`: withExists('comments'). */
2025
+ withExists<const S extends readonly LooseSpec[]>(...relations: Aggregates<M, S>): this;
2026
+ withExists(this: Builder$1<UntypedModel>, ...relations: LooseSpec[]): this;
2145
2027
  /**
2146
- * Registers observers: every method named after a model event (created, updating, …) becomes a listener.
2147
- * Observer classes are resolved from the container.
2028
+ * Laravel's withAggregate(): a correlated subquery per relation, `select <fn>(<related column>) … as <alias>`, the
2029
+ * alias being `<relation>_<fn>_<column>` unless the relation is named `'orders as alias'`. The relation's
2030
+ * constraint and the related model's global scopes apply; orderings are dropped. 'exists' selects
2031
+ * `exists (…)`, cast to a boolean. Without a function the column's first value is selected.
2148
2032
  */
2149
- static observe(...observers: Array<object | (new () => object)>): void;
2033
+ withAggregate<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression, fn?: string): this;
2034
+ withAggregate(this: Builder$1<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression, fn?: string): this;
2035
+ /** Casts for selected columns, as if the model declared them: withCasts({ orders_sum_price: 'float' }). */
2036
+ withCasts(casts: Readonly<Record<string, CastDefinition>>): this;
2150
2037
  /**
2151
- * Turns the relation guard on or off: while it is on, reading a property of a relation method as if it were the
2152
- * related model (`post.author.name`) warns once with how to read the relation. DatabaseServiceProvider turns it on
2153
- * outside production. Turning it on again forgets which warnings were given.
2038
+ * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').
2039
+ * Uses `exists (…)` for the common "at least one"/"none" cases and a count subquery otherwise.
2154
2040
  */
2155
- static warnOnRelationPropertyAccess(enabled?: boolean): void;
2156
- static warnsOnRelationPropertyAccess(): boolean;
2157
- /** Runs fn with model events off, for this async context only. */
2158
- static withoutEvents<R>(fn: () => R): R;
2159
- /** A new query of this model, with its global scopes. */
2160
- static query<C extends typeof Model>(this: C): ModelBuilder<C>;
2161
- static where<C extends typeof Model>(this: C, ...args: WhereArgs<Instance<C>, ModelBuilder<C>>): ModelBuilder<C>;
2162
- /** Post.when(request.query('q'), (query, q) => query.whereLike('title', `%${q}%`)): a new query, then when(). */
2163
- static when<C extends typeof Model, V>(this: C, value: (query: ModelBuilder<C>) => V, callback: (query: ModelBuilder<C>, value: Truthy<V>) => unknown, otherwise?: (query: ModelBuilder<C>, value: V) => unknown): ModelBuilder<C>;
2164
- static when<C extends typeof Model, V>(this: C, value: V, callback: (query: ModelBuilder<C>, value: Truthy<V>) => unknown, otherwise?: (query: ModelBuilder<C>, value: V) => unknown): ModelBuilder<C>;
2165
- /** A new query, then unless(): the callback runs when the value is falsy. */
2166
- static unless<C extends typeof Model, V>(this: C, value: (query: ModelBuilder<C>) => V, callback: (query: ModelBuilder<C>, value: V) => unknown, otherwise?: (query: ModelBuilder<C>, value: Truthy<V>) => unknown): ModelBuilder<C>;
2167
- static unless<C extends typeof Model, V>(this: C, value: V, callback: (query: ModelBuilder<C>, value: V) => unknown, otherwise?: (query: ModelBuilder<C>, value: Truthy<V>) => unknown): ModelBuilder<C>;
2168
- static whereKey<C extends typeof Model>(this: C, id: unknown): ModelBuilder<C>;
2169
- static whereIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C>;
2170
- static whereNotIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C>;
2171
- static whereNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C>;
2172
- static whereNotNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C>;
2173
- static whereBetween<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly [unknown, unknown]): ModelBuilder<C>;
2174
- /** Post.whereLike('title', `%${term}%`): case-insensitive unless caseSensitive (see the query builder's whereLike()). */
2175
- static whereLike<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, value: string, caseSensitive?: boolean): ModelBuilder<C>;
2176
- static whereNotLike<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, value: string, caseSensitive?: boolean): ModelBuilder<C>;
2177
- /** Post.whereDate('published_at', '2026-01-05'), Post.whereDate('published_at', '<', new Date()). */
2178
- static whereDate<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
2179
- static whereTime<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
2180
- static whereDay<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
2181
- static whereMonth<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
2182
- static whereYear<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
2183
- static whereColumn<C extends typeof Model>(this: C, first: Column<Instance<C>>, operatorOrSecond: string, second?: Column<Instance<C>>): ModelBuilder<C>;
2184
- static whereRaw<C extends typeof Model>(this: C, sql: string, bindings?: readonly unknown[]): ModelBuilder<C>;
2185
- static select<C extends typeof Model>(this: C, ...columns: Array<Column<Instance<C>> | Expression>): ModelBuilder<C>;
2186
- static orderBy<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, direction?: Direction): ModelBuilder<C>;
2187
- static latest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C>;
2188
- static oldest<C extends typeof Model>(this: C, column?: Column<Instance<C>>): ModelBuilder<C>;
2189
- static inRandomOrder<C extends typeof Model>(this: C): ModelBuilder<C>;
2190
- static limit<C extends typeof Model>(this: C, count: number): ModelBuilder<C>;
2191
- static take<C extends typeof Model>(this: C, count: number): ModelBuilder<C>;
2192
- static withoutGlobalScope<C extends typeof Model>(this: C, scope: string | ScopeClass): ModelBuilder<C>;
2193
- static withoutGlobalScopes<C extends typeof Model>(this: C, scopes?: Array<string | ScopeClass>): ModelBuilder<C>;
2194
- /** Eager loads relations: Post.with('author', 'comments.user').get(). */
2195
- static with<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C>;
2196
- static withCount<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C>;
2197
- /** Post.withSum('orders', 'price'): adds orders_sum_price. */
2198
- static withSum<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C>;
2199
- static withAvg<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C>;
2200
- static withMin<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C>;
2201
- static withMax<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C>;
2202
- static withExists<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C>;
2203
- static withAggregate<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): ModelBuilder<C>;
2204
- static has<C extends typeof Model>(this: C, relation: string, operator?: string, count?: number): ModelBuilder<C>;
2205
- static whereHas<C extends typeof Model>(this: C, relation: string, callback?: RelationConstraint, operator?: string, count?: number): ModelBuilder<C>;
2206
- static doesntHave<C extends typeof Model>(this: C, relation: string): ModelBuilder<C>;
2207
- static whereDoesntHave<C extends typeof Model>(this: C, relation: string, callback?: RelationConstraint): ModelBuilder<C>;
2208
- /** Soft deletes: include trashed rows. */
2209
- static withTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
2210
- /** Soft deletes: only trashed rows. */
2211
- static onlyTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
2212
- static withoutTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
2213
- static all<C extends typeof Model>(this: C): Promise<EloquentCollection<Instance<C>>>;
2214
- static find<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | undefined>;
2215
- static findOrFail<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>;
2216
- static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C>>;
2217
- static findMany<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>;
2218
- static first<C extends typeof Model>(this: C): Promise<Instance<C> | undefined>;
2219
- static firstOrFail<C extends typeof Model>(this: C): Promise<Instance<C>>;
2220
- static firstWhere<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, operatorOrValue: unknown, value?: unknown): Promise<Instance<C> | undefined>;
2221
- static count(): Promise<number>;
2222
- static exists(): Promise<boolean>;
2223
- static pluck<C extends typeof Model, V = unknown>(this: C, column: Column<Instance<C>>): Promise<Collection<V>>;
2224
- static paginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<LengthAwarePaginator<Instance<C>>>;
2225
- static simplePaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<Paginator<Instance<C>>>;
2226
- static cursorPaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], cursorName?: string, cursor?: Cursor | string): Promise<CursorPaginator<Instance<C>>>;
2227
- static chunk<C extends typeof Model>(this: C, count: number, callback: (models: EloquentCollection<Instance<C>>, page: number) => unknown): Promise<boolean>;
2228
- static chunkById<C extends typeof Model>(this: C, count: number, callback: (models: EloquentCollection<Instance<C>>, page: number) => unknown): Promise<boolean>;
2229
- static each<C extends typeof Model>(this: C, callback: (model: Instance<C>, index: number) => unknown, count?: number): Promise<boolean>;
2230
- static lazy<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>>;
2231
- static lazyById<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>>;
2232
- /** Creates and saves a model (mass assignment rules apply). */
2233
- static create<C extends typeof Model>(this: C, attributes?: Row): Promise<Instance<C>>;
2234
- static forceCreate<C extends typeof Model>(this: C, attributes: Row): Promise<Instance<C>>;
2235
- static firstOrNew<C extends typeof Model>(this: C, attributes: Row, values?: Row): Promise<Instance<C>>;
2236
- static firstOrCreate<C extends typeof Model>(this: C, attributes: Row, values?: Row): Promise<Instance<C>>;
2237
- static updateOrCreate<C extends typeof Model>(this: C, attributes: Row, values?: Row): Promise<Instance<C>>;
2041
+ has<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, operator?: string, count?: number, boolean?: 'and' | 'or', callback?: RelationConstraint): this;
2042
+ has(this: Builder$1<UntypedModel>, relation: string, operator?: string, count?: number, boolean?: 'and' | 'or', callback?: RelationConstraint): this;
2043
+ orHas<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, operator?: string, count?: number): this;
2044
+ orHas(this: Builder$1<UntypedModel>, relation: string, operator?: string, count?: number): this;
2045
+ doesntHave<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, boolean?: 'and' | 'or', callback?: RelationConstraint): this;
2046
+ doesntHave(this: Builder$1<UntypedModel>, relation: string, boolean?: 'and' | 'or', callback?: RelationConstraint): this;
2047
+ orDoesntHave<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>): this;
2048
+ orDoesntHave(this: Builder$1<UntypedModel>, relation: string): this;
2049
+ /** Rows with related rows matching the callback: whereHas('comments', (q) => q.where('approved', true)). */
2050
+ whereHas<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, callback?: RelationConstraint, operator?: string, count?: number): this;
2051
+ whereHas(this: Builder$1<UntypedModel>, relation: string, callback?: RelationConstraint, operator?: string, count?: number): this;
2052
+ orWhereHas<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, callback?: RelationConstraint, operator?: string, count?: number): this;
2053
+ orWhereHas(this: Builder$1<UntypedModel>, relation: string, callback?: RelationConstraint, operator?: string, count?: number): this;
2054
+ whereDoesntHave<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, callback?: RelationConstraint): this;
2055
+ whereDoesntHave(this: Builder$1<UntypedModel>, relation: string, callback?: RelationConstraint): this;
2056
+ orWhereDoesntHave<const N extends RelationPath<M> | (string & {})>(relation: RelationPathArg<M, N>, callback?: RelationConstraint): this;
2057
+ orWhereDoesntHave(this: Builder$1<UntypedModel>, relation: string, callback?: RelationConstraint): this;
2058
+ /** has('comments.author'): whereHas('comments', q => q.has('author')) */
2059
+ private hasNested;
2060
+ private normalizeRelationSpecs;
2061
+ /** Models from raw rows, marked as existing. */
2062
+ hydrate(rows: readonly Row[]): M[];
2063
+ aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown>;
2064
+ exists(): Promise<boolean>;
2065
+ /** The column's values, through the model's casts and accessors. */
2066
+ pluck<V = unknown>(column: Column<M>): Promise<Collection<V>>;
2067
+ /** Whether `id` can't be one of the model's unique ids (not a UUID for HasUuids): it matches no row. */
2068
+ protected isMalformedKey(id: unknown): boolean;
2238
2069
  /**
2239
- * The model's registered factory (database/factories/<Model>Factory.ts): await User.factory().create(),
2240
- * await User.factory(3).create(). Use UserFactory.new() to reach the factory's own state methods with their types.
2070
+ * A model by its key, or undefined; with an array of keys, the models found, as a collection (Laravel's find()). A
2071
+ * malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. A key typed
2072
+ * `unknown` (a request input) may be an array at run time, so its result is a model or a collection.
2241
2073
  */
2242
- static factory<C extends typeof Model>(this: C): Factory<InstanceType<C>>;
2243
- static factory<C extends typeof Model>(this: C, count: number, state?: State): Factory<InstanceType<C>> & Many;
2244
- /** Deletes models by key, one by one, so model events fire. Returns how many were deleted. */
2245
- static destroy(...ids: Array<unknown | unknown[]>): Promise<number>;
2246
- /** Disables mass assignment protection everywhere until reguard(). */
2247
- static unguard(state?: boolean): void;
2248
- static reguard(): void;
2249
- static isUnguarded(): boolean;
2250
- /** Runs fn with mass assignment protection off, for this async context only (seeders, factories). */
2251
- static unguarded<R>(fn: () => R): R;
2252
- /** Sets the fillable attributes; the others are dropped, or throw MassAssignmentError on a totally guarded model. */
2253
- fill(attributes: Row): this;
2254
- /** Sets attributes with no mass assignment check. Never pass it request input. */
2255
- forceFill(attributes: Row): this;
2256
- isFillable(key: string): boolean;
2257
- /** Guarded names match case-insensitively: SQLite and MySQL column names are case-insensitive. */
2258
- isGuarded(key: string): boolean;
2259
- totallyGuarded(): boolean;
2260
- getFillable(): string[];
2261
- getGuarded(): string[];
2262
- /** An attribute through its accessor or cast; undefined when the model doesn't have it. */
2263
- getAttribute<T = unknown>(key: string): T;
2264
- /** The attribute's value after its accessor (get<Name>Attribute) or cast. */
2265
- getAttributeValue(key: string): unknown;
2266
- /** Sets an attribute through its mutator (set<Name>Attribute) or cast. */
2267
- setAttribute(key: string, value: unknown): this;
2268
- hasGetMutator(key: string): boolean;
2269
- hasSetMutator(key: string): boolean;
2270
- /** Every cast, including the implied ones: the incrementing key (int) and the timestamp columns (datetime). */
2271
- getCasts(): Record<string, CastDefinition>;
2272
- /** Adds casts to this instance only (Laravel's mergeCasts()); withCasts() on a query does it for each result. */
2273
- mergeCasts(casts: Readonly<Record<string, CastDefinition>>): this;
2274
- hasCast(key: string, types?: string[]): boolean;
2275
- /** The stored attributes, with in-place changes to json casts written back. */
2276
- getAttributes(): Row;
2277
- /** Replaces the stored attributes as-is (no casts or mutators); sync = also make them the original. */
2278
- setRawAttributes(attributes: Row, sync?: boolean): this;
2279
- /** The original value (cast), or every original value. */
2280
- getOriginal(): Row;
2281
- getOriginal<T = unknown>(key: string): T;
2282
- getRawOriginal(): Row;
2283
- getRawOriginal<T = unknown>(key: string): T;
2284
- syncOriginal(): this;
2285
- syncOriginalAttributes(...keys: string[]): this;
2286
- /** The attributes that changed since the model was loaded or saved, compared by meaning (casts), not representation. */
2287
- getDirty(): Row;
2288
- isDirty(...keys: Array<string | string[]>): boolean;
2289
- isClean(...keys: Array<string | string[]>): boolean;
2290
- /** The attributes the last save() changed. */
2291
- getChanges(): Row;
2292
- wasChanged(...keys: Array<string | string[]>): boolean;
2293
- syncChanges(): this;
2294
- /** The given attributes (through accessors and casts). */
2295
- only(...keys: Array<string | string[]>): Row;
2074
+ find(ids: readonly unknown[]): Promise<EloquentCollection<M>>;
2075
+ find(id: ModelKey | null | undefined): Promise<M | undefined>;
2076
+ find(id: unknown): Promise<M | EloquentCollection<M> | undefined>;
2077
+ findMany(ids: readonly unknown[]): Promise<EloquentCollection<M>>;
2078
+ /** find(), or ModelNotFoundError (a 404). With an array, every id must exist. */
2079
+ findOrFail(ids: readonly unknown[]): Promise<EloquentCollection<M>>;
2080
+ findOrFail(id: ModelKey | null | undefined): Promise<M>;
2081
+ findOrFail(id: unknown): Promise<M | EloquentCollection<M>>;
2082
+ findOr<R>(ids: readonly unknown[], callback: () => R | Promise<R>): Promise<EloquentCollection<M> | R>;
2083
+ findOr<R>(id: ModelKey | null | undefined, callback: () => R | Promise<R>): Promise<M | R>;
2084
+ findOr<R>(id: unknown, callback: () => R | Promise<R>): Promise<M | EloquentCollection<M> | R>;
2085
+ firstOrFail(): Promise<M>;
2086
+ firstOr<R>(callback: () => R | Promise<R>): Promise<M | R>;
2087
+ firstWhere(column: Column<M> | Expression, operatorOrValue: unknown, value?: unknown): Promise<M | undefined>;
2088
+ /** A new, unsaved model of this query's class (mass assignment rules apply). */
2089
+ newModelInstance(attributes?: Row): M;
2090
+ /** With generated types, `attributes` is checked (WriteAttributes): each key a column or a set mutator's, each value its type. */
2091
+ make<const T extends object = Row>(attributes?: T & WriteAttributes<M, T>): M;
2092
+ make(this: Builder$1<UntypedModel>, attributes?: Row): M;
2093
+ create<const T extends object = Row>(attributes?: T & WriteAttributes<M, T>): Promise<M>;
2094
+ create(this: Builder$1<UntypedModel>, attributes?: Row): Promise<M>;
2095
+ /** Creates without mass assignment protection. Never pass it request input. */
2096
+ forceCreate<const T extends object = Row>(attributes: T & WriteAttributes<M, T>): Promise<M>;
2097
+ forceCreate(this: Builder$1<UntypedModel>, attributes: Row): Promise<M>;
2098
+ /** The first match, or a new unsaved model with attributes + values. */
2099
+ firstOrNew<const A extends object = Row, const V extends object = Row>(attributes: A & WriteAttributes<M, A>, values?: V & WriteAttributes<M, V>): Promise<M>;
2100
+ firstOrNew(this: Builder$1<UntypedModel>, attributes: Row, values?: Row): Promise<M>;
2101
+ /** The first match, or a new saved model. A concurrent insert of the same unique key returns that row instead. */
2102
+ firstOrCreate<const A extends object = Row, const V extends object = Row>(attributes: A & WriteAttributes<M, A>, values?: V & WriteAttributes<M, V>): Promise<M>;
2103
+ firstOrCreate(this: Builder$1<UntypedModel>, attributes: Row, values?: Row): Promise<M>;
2104
+ /** Tries to create; on a unique constraint violation, returns the existing row (Laravel's createOrFirst()). */
2105
+ createOrFirst<const A extends object = Row, const V extends object = Row>(attributes: A & WriteAttributes<M, A>, values?: V & WriteAttributes<M, V>): Promise<M>;
2106
+ createOrFirst(this: Builder$1<UntypedModel>, attributes: Row, values?: Row): Promise<M>;
2107
+ /** Updates the first match with values, or creates it. */
2108
+ updateOrCreate<const A extends object = Row, const V extends object = Row>(attributes: A & WriteAttributes<M, A>, values?: V & WriteAttributes<M, V>): Promise<M>;
2109
+ updateOrCreate(this: Builder$1<UntypedModel>, attributes: Row, values?: Row): Promise<M>;
2110
+ /** Mass update (no model events); sets updated_at when the model uses timestamps. */
2111
+ update<const T extends object = Row>(values: T & WriteAttributes<M, T>): Promise<number>;
2112
+ update(this: Builder$1<UntypedModel>, values: Row): Promise<number>;
2113
+ /** Mass delete (no model events). With soft deletes this sets deleted_at on the matching rows instead. */
2114
+ delete(): Promise<number>;
2115
+ /** Deletes the matching rows for real, even with soft deletes. */
2116
+ forceDelete(): Promise<number>;
2117
+ /** Includes soft-deleted rows (withTrashed(false) is withoutTrashed()). */
2118
+ withTrashed(withTrashed?: boolean): this;
2119
+ /** Excludes soft-deleted rows explicitly. */
2120
+ withoutTrashed(): this;
2121
+ /** Only soft-deleted rows. */
2122
+ onlyTrashed(): this;
2123
+ /** Restores every matching row (deleted_at = null), trashed or not. */
2124
+ restore(): Promise<number>;
2125
+ protected addUpdatedAtColumn(values: Row): Row;
2126
+ toSql(): string;
2127
+ getBindings(): unknown[];
2128
+ clone(): Builder$1<M>;
2129
+ /** Nested where groups get a builder of the same model (without global scopes), so local scopes work inside them. */
2130
+ newQuery(): Builder<Row>;
2131
+ /** chunk() and lazy() order by the primary key when the query has no order. */
2132
+ protected enforceOrderBy(): void;
2133
+ protected defaultKeyName(): string;
2134
+ protected defaultPerPage(): number;
2135
+ }
2136
+
2137
+ /**
2138
+ * Laravel's Eloquent collection: what every query, relation and eager load of models returns. It is a support
2139
+ * Collection (methods that keep the items keep this class; map() and the other type-changing methods return a plain
2140
+ * Collection) with the model-aware methods: find() by key, load() and loadCount() for every model at once, fresh(),
2141
+ * modelKeys(), toQuery(), and diff()/intersect()/unique()/only()/except()/merge() that compare models by key.
2142
+ */
2143
+ declare class EloquentCollection<M extends Model = Model> extends Collection<M> {
2144
+ /** The model with this key (or this model's key), else the default; with several keys, those models. */
2145
+ find(key: readonly unknown[] | Collection<unknown>): this;
2146
+ find(key: ModelKey | Model | null | undefined): M | undefined;
2147
+ find<D>(key: ModelKey | Model | null | undefined, defaultValue: D): M | D;
2148
+ /** A key typed `unknown` may be a list at run time: a model or this collection's kind. */
2149
+ find(key: unknown): M | this | undefined;
2150
+ find<D>(key: unknown, defaultValue: D): M | this | D;
2151
+ /** find(), or ModelNotFoundError naming the missing keys. */
2152
+ findOrFail(keys: readonly unknown[] | Collection<unknown>): this;
2153
+ findOrFail(key: ModelKey | Model | null | undefined): M;
2154
+ findOrFail(key: unknown): M | this;
2155
+ /** The primary keys, in order. */
2156
+ modelKeys(): unknown[];
2157
+ /** The models keyed by their primary key (as text). */
2158
+ getDictionary(items?: Iterable<M>): Record<string, M>;
2159
+ /** The same models in a plain Collection. */
2160
+ toBase(): Collection<M>;
2161
+ /** Whether a model with this key (or this model) is in the collection; the other forms are Collection's. */
2162
+ contains(key: keyof M & string, value: unknown): boolean;
2163
+ contains(key: (keyof M & string) | ((item: M) => unknown), operator: Operator$1, value: unknown): boolean;
2164
+ contains(callback: (item: M) => boolean): boolean;
2165
+ contains(value: unknown): boolean;
2166
+ /** Collection's containsStrict(): a model matches only itself (no key matching). */
2167
+ containsStrict(key: keyof M & string, value: unknown): boolean;
2168
+ containsStrict(callback: (item: M) => boolean): boolean;
2169
+ containsStrict(value: unknown): boolean;
2170
+ /** Collection's doesntContainStrict(): a model matches only itself (no key matching). */
2171
+ doesntContainStrict(key: keyof M & string, value: unknown): boolean;
2172
+ doesntContainStrict(callback: (item: M) => boolean): boolean;
2173
+ doesntContainStrict(value: unknown): boolean;
2174
+ /** Eager loads relations onto every model, one query per relation: await posts.load('author', 'comments.author'). */
2175
+ load<const S extends readonly LooseSpec[]>(...relations: EagerLoads<M, S>): Promise<EloquentCollection<WithLoaded<M, LoadedTree<S>>> & this>;
2176
+ load(this: EloquentCollection<UntypedModel>, ...relations: LooseSpec[]): Promise<this>;
2177
+ /** Loads only the relations that aren't loaded yet; nested paths are followed into the loaded relations. */
2178
+ loadMissing<const S extends readonly string[]>(...relations: EagerLoads<M, S>): Promise<EloquentCollection<WithLoaded<M, LoadedTree<S>>> & this>;
2179
+ loadMissing(this: EloquentCollection<UntypedModel>, ...relations: string[]): Promise<this>;
2180
+ /** Adds <relation>_count attributes to every model with one query: await posts.loadCount('comments'). */
2181
+ loadCount<const S extends readonly LooseSpec[]>(...relations: Aggregates<M, S>): Promise<this>;
2182
+ loadCount(this: EloquentCollection<UntypedModel>, ...relations: LooseSpec[]): Promise<this>;
2296
2183
  /**
2297
- * useCache = false skips the json-cast decode cache entirely (both reading and writing it): used by getOriginal(),
2298
- * so a decoded original never aliases the live attribute's cached (and possibly in-place-mutated) object, even
2299
- * when their raw stored strings are equal right after load/save.
2184
+ * Laravel's loadAggregate(): withAggregate() for models already loaded, with one query for the whole collection.
2185
+ * The values become clean attributes (with their casts: loadExists() gives booleans).
2300
2186
  */
2301
- protected castAttribute(key: string, value: unknown, useCache?: boolean): unknown;
2302
- /** Writes json casts that were changed in place (post.meta.views++) back into the stored attributes. */
2303
- protected mergeCachedCasts(): void;
2304
- private mutatorFor;
2305
- getKeyName(): string;
2306
- getKeyType(): 'int' | 'string';
2307
- getIncrementing(): boolean;
2308
- /** Whether new rows get unique string ids before `creating` (HasUuids, HasUlids). */
2309
- usesUniqueIds(): boolean;
2310
- /** The columns that get a unique id (HasUuids and HasUlids: the primary key). */
2311
- uniqueIds(): string[];
2312
- /** A new unique id (HasUuids: a version 7 UUID; HasUlids: a lower-case ULID). */
2313
- newUniqueId(): string | undefined;
2314
- /** Whether a value has the shape of this model's unique ids (HasUuids: a UUID). Any value passes by default. */
2315
- isValidUniqueId(_value: unknown): boolean;
2316
- /** Fills each empty unique id column with newUniqueId() (Laravel's setUniqueIds()). */
2317
- setUniqueIds(): void;
2318
- getKey(): unknown;
2319
- getTable(): string;
2320
- getConnectionName(): string | undefined;
2321
- getPerPage(): number;
2322
- /** 'posts.title' for 'title'. Already-qualified columns are returned as-is. */
2323
- qualifyColumn(column: string): string;
2324
- getQualifiedKeyName(): string;
2325
- /** The conventional foreign key pointing at this model: user_id for User. */
2326
- getForeignKey(): string;
2327
- getRouteKeyName(): string;
2328
- getRouteKey(): unknown;
2187
+ loadAggregate<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression, fn?: string): Promise<this>;
2188
+ loadAggregate(this: EloquentCollection<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression, fn?: string): Promise<this>;
2189
+ /** Adds <relation>_sum_<column> to every model: await users.loadSum('orders', 'price'). */
2190
+ loadSum<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): Promise<this>;
2191
+ loadSum(this: EloquentCollection<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this>;
2192
+ loadAvg<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): Promise<this>;
2193
+ loadAvg(this: EloquentCollection<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this>;
2194
+ loadMin<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): Promise<this>;
2195
+ loadMin(this: EloquentCollection<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this>;
2196
+ loadMax<const S extends LooseSpec | readonly LooseSpec[]>(relations: AggregateSpecs<M, S>, column: string | Expression): Promise<this>;
2197
+ loadMax(this: EloquentCollection<UntypedModel>, relations: LooseSpec | readonly LooseSpec[], column: string | Expression): Promise<this>;
2198
+ /** Adds a boolean <relation>_exists to every model. */
2199
+ loadExists<const S extends readonly LooseSpec[]>(...relations: Aggregates<M, S>): Promise<this>;
2200
+ loadExists(this: EloquentCollection<UntypedModel>, ...relations: LooseSpec[]): Promise<this>;
2201
+ /** The models as they are in the database now (without global scopes), with relations loaded; deleted ones drop out. */
2202
+ fresh(...relations: EagerLoadSpec[]): Promise<this>;
2203
+ /** The models whose keys aren't in the given models. */
2204
+ diff(items: Iterable<M>): this;
2205
+ /** The models whose keys are also in the given models. */
2206
+ intersect(items: Iterable<M>): this;
2207
+ /** One model per key (the last instance, at the first one's place); with a key or callback, Collection's unique(). */
2208
+ unique(key?: (keyof M & string) | ((item: M) => unknown)): this;
2209
+ /** The models with these keys, in the collection's order. */
2210
+ only(...keys: unknown[]): this;
2211
+ /** The models without these keys, in the collection's order. */
2212
+ except(...keys: unknown[]): this;
2213
+ /** Adds the given models, replacing the ones with the same key. */
2214
+ merge(items: Iterable<M>): this;
2215
+ makeHidden(...attributes: Array<string | string[]>): this;
2216
+ makeVisible(...attributes: Array<string | string[]>): this;
2217
+ setVisible(visible: string[]): this;
2218
+ setHidden(hidden: string[]): this;
2219
+ append(...attributes: Array<string | string[]>): this;
2220
+ /** A query of exactly these models (where key in …), for mass updates: await posts.toQuery().update({ … }). */
2221
+ toQuery(): Builder$1<M>;
2222
+ }
2223
+
2224
+ /** What a paginator's getCollection() holds: the models' Eloquent collection, else a Collection. */
2225
+ type PageCollection<T> = [T] extends [Model] ? EloquentCollection<T> : Collection<T>;
2226
+ interface PaginatorOptions {
2227
+ /** The base URL of the page links (default: the current request's URL, or '/'). */
2228
+ path?: string;
2229
+ /** Extra query string values added to every link. */
2230
+ query?: Record<string, unknown>;
2231
+ fragment?: string;
2232
+ pageName?: string;
2233
+ }
2234
+ /** Laravel's Arr::query(): nested values become key[0]=…, encoded as RFC 3986. */
2235
+ declare function buildQuery(values: Record<string, unknown>, prefix?: string): string;
2236
+ /**
2237
+ * Shared paginator state and URL building (Laravel's AbstractPaginator).
2238
+ * The static resolvers read the current request; DatabaseServiceProvider points them at HttpRequest.
2239
+ */
2240
+ declare abstract class AbstractPaginator<T> implements Iterable<T> {
2241
+ protected readonly perPageValue: number;
2242
+ static currentPathResolver: () => string;
2243
+ static currentPageResolver: (pageName: string) => number;
2244
+ static queryStringResolver: () => Record<string, unknown>;
2245
+ static currentCursorResolver: (cursorName: string) => unknown;
2246
+ static resolveCurrentPath(): string;
2247
+ static resolveCurrentPage(pageName?: string): number;
2248
+ /** Restores the defaults (page 1, path '/'). Used by tests and when the provider is torn down. */
2249
+ static resetResolvers(): void;
2250
+ protected collection: Collection<T>;
2251
+ protected pathValue: string;
2252
+ protected queryValues: Record<string, unknown>;
2253
+ protected fragmentValue: string | undefined;
2254
+ protected pageName: string;
2255
+ /** The resolved page number: page-based paginators pass it in; cursor pagination never reads it. */
2256
+ protected readonly currentPageValue: number;
2257
+ onEachSideCount: number;
2258
+ protected constructor(items: Iterable<T>, perPageValue: number, options: PaginatorOptions, currentPage?: number);
2259
+ currentPage(): number;
2260
+ /** The 1-based position of the first item on this page, or null when the page is empty. */
2261
+ firstItem(): number | null;
2262
+ lastItem(): number | null;
2263
+ onFirstPage(): boolean;
2264
+ previousPageUrl(): string | null;
2265
+ /** The URL for a page number: path?query&page=n#fragment. */
2266
+ url(page: number): string;
2267
+ protected buildFragment(): string;
2268
+ path(): string;
2269
+ withPath(path: string): this;
2270
+ setPath(path: string): this;
2271
+ /** Adds values to every link's query string. */
2272
+ appends(key: string | Record<string, unknown>, value?: unknown): this;
2273
+ /** Keeps the current request's query string on every link. */
2274
+ withQueryString(): this;
2275
+ fragment(fragment: string): this;
2276
+ getPageName(): string;
2277
+ setPageName(name: string): this;
2278
+ onEachSide(count: number): this;
2279
+ /** The items on this page, as an array (Laravel's items()). */
2280
+ items(): T[];
2281
+ /** The items on this page: an Eloquent query's in its models' Eloquent collection, as Laravel's. */
2282
+ getCollection(): PageCollection<T>;
2283
+ setCollection(items: Collection<T>): this;
2329
2284
  /**
2330
- * The model a route parameter value points at: where <field or route key> = value (global scopes apply, so a
2331
- * soft-deleted row isn't found). A non-numeric value for an integer primary key, or a value that isn't a UUID
2332
- * (ULID) for a unique id column, finds nothing without a query.
2285
+ * Transforms each item in place, typically for serialization, and returns this paginator typed with the new items:
2286
+ * `posts.through((post) => ({ id: post.id }))`. Each paginator narrows the return type to its own class.
2333
2287
  */
2334
- resolveRouteBinding(value: string, field?: string): Promise<this | undefined>;
2335
- /** Override to customize the binding query (Laravel's resolveRouteBindingQuery()). */
2336
- resolveRouteBindingQuery(query: Builder<this>, value: string, field: string): Builder<this>;
2337
- usesTimestamps(): boolean;
2338
- usesSoftDeletes(): boolean;
2339
- getCreatedAtColumn(): string | null;
2340
- getUpdatedAtColumn(): string | null;
2341
- getDeletedAtColumn(): string;
2342
- /** The model's database connection, from the DatabaseManager binding. */
2343
- getConnection(): Connection;
2344
- setConnection(name: string | undefined): this;
2345
- setTable(table: string): this;
2346
- /** A new instance of the same class, connection and table (mass assignment rules apply to attributes). */
2347
- newInstance(attributes?: Row, exists?: boolean): this;
2348
- /** An existing model from a database row (no casts or mutators applied to the row). */
2349
- newFromBuilder(attributes: Row): this;
2350
- /** A query of this model with its global scopes and default eager loads. */
2351
- newQuery(): Builder<this>;
2352
- /** A query with the default eager loads (`with`, `withCount`) but no global scopes. */
2353
- newQueryWithoutScopes(): Builder<this>;
2354
- /** A query with the global scopes but no default eager loads. */
2355
- newQueryWithoutRelationships(): Builder<this>;
2356
- /** Adds this class's global scopes to a builder (relations use it for the related model's scopes). */
2357
- registerGlobalScopes<B extends Builder<Model>>(builder: B): B;
2288
+ through<U>(callback: (item: T, index: number) => U): AbstractPaginator<U>;
2289
+ perPage(): number;
2290
+ count(): number;
2291
+ isEmpty(): boolean;
2292
+ isNotEmpty(): boolean;
2293
+ [Symbol.iterator](): Iterator<T>;
2294
+ protected itemsToArray(): unknown[];
2295
+ abstract toArray(): Record<string, unknown>;
2296
+ toJSON(): Record<string, unknown>;
2297
+ toJson(): string;
2298
+ }
2299
+
2300
+ /** A position in a cursor-paginated result: the ordered columns' values of an edge item, plus the direction. */
2301
+ declare class Cursor {
2302
+ protected readonly parameters: Record<string, unknown>;
2303
+ protected readonly pointsToNext: boolean;
2304
+ constructor(parameters: Record<string, unknown>, pointsToNext?: boolean);
2305
+ parameter(name: string): unknown;
2306
+ pointsToNextItems(): boolean;
2307
+ pointsToPreviousItems(): boolean;
2308
+ toArray(): Record<string, unknown>;
2309
+ /** URL-safe base64 of the JSON parameters (Laravel's format). */
2310
+ encode(): string;
2311
+ /** Decodes a cursor from the query string. Anything malformed gives undefined (the first page). */
2312
+ static fromEncoded(encoded: unknown): Cursor | undefined;
2313
+ }
2314
+ interface CursorPaginatorOptions extends Omit<PaginatorOptions, 'pageName'> {
2315
+ cursorName?: string;
2316
+ /** The ordered columns whose values make up each cursor. */
2317
+ parameters: string[];
2318
+ }
2319
+ /**
2320
+ * cursorPaginate(): "next"/"previous" by the ordered columns' values instead of an offset, so it stays fast and
2321
+ * stable on large, changing tables (Laravel's CursorPaginator). JSON: data, path, per_page, next_cursor,
2322
+ * next_page_url, prev_cursor, prev_page_url.
2323
+ */
2324
+ declare class CursorPaginator<T> extends AbstractPaginator<T> {
2325
+ protected readonly cursorValue: Cursor | undefined;
2326
+ protected readonly hasMore: boolean;
2327
+ protected readonly cursorName: string;
2328
+ protected readonly parameters: string[];
2329
+ constructor(items: Iterable<T>, perPage: number, cursorValue: Cursor | undefined, options: CursorPaginatorOptions);
2330
+ /** The cursor in the current request's query string (?cursor=…), if any. */
2331
+ static resolveCurrentCursor(cursorName?: string): Cursor | undefined;
2332
+ cursor(): Cursor | undefined;
2333
+ getCursorName(): string;
2334
+ through<U>(callback: (item: T, index: number) => U): CursorPaginator<U>;
2335
+ hasMorePages(): boolean;
2336
+ onFirstPage(): boolean;
2337
+ nextCursor(): Cursor | undefined;
2338
+ previousCursor(): Cursor | undefined;
2339
+ nextPageUrl(): string | null;
2340
+ previousPageUrl(): string | null;
2341
+ /** The URL for a cursor: path?query&cursor=…#fragment. */
2342
+ url(cursor: Cursor | number): string;
2343
+ protected cursorFor(item: T, pointsToNext: boolean): Cursor;
2344
+ toArray(): Record<string, unknown>;
2345
+ }
2346
+
2347
+ type Sql = RawBuilder<unknown>;
2348
+ /** The operators accepted by where()/having(). Anything else is rejected: operators are written into the SQL. */
2349
+ declare const OPERATORS: Set<string>;
2350
+ /**
2351
+ * Compiles a query builder's state into a Kysely `sql` template for one driver, like Laravel's Query\Grammars.
2352
+ * Identifiers go through sql.id() (quoted per dialect); values are always bound parameters.
2353
+ */
2354
+ declare class Grammar {
2355
+ readonly driver: DriverName;
2356
+ constructor(driver: DriverName);
2357
+ /** 'users.name' → "users"."name", 'users.*' → "users".*, 'name as n' → "name" as "n". Expressions pass through raw. */
2358
+ wrap(value: string | Expression): Sql;
2359
+ wrapTable(table: string | Expression): Sql;
2360
+ prepare(value: unknown): unknown;
2361
+ /** A bound value, the raw SQL of an Expression, or a Kysely sql fragment as-is. */
2362
+ parameter(value: unknown): Sql;
2363
+ operator(operator: string): string;
2364
+ columnize(columns: ReadonlyArray<string | Expression>): Sql;
2365
+ compileSelect(query: Builder<unknown>, extraColumn?: Sql): Sql;
2358
2366
  /**
2359
- * Adds this class's default `with` and `withCount` to a builder (relations use it for the related model's
2360
- * defaults). A default count that reaches the same class again while it is being added (a self-referencing
2361
- * relation, or two models counting each other) is skipped there instead of recursing forever.
2367
+ * Laravel 11's compileGroupLimit(): the query numbers its rows per `column` in its own order, and an outer query keeps
2368
+ * those inside the limit and offset, in row-number order. SQLite 3.25+, MySQL 8 and PostgreSQL have window functions.
2362
2369
  */
2363
- registerDefaultEagerLoads<B extends Builder<Model>>(builder: B): B;
2364
- /** A bare builder for this model: no global scopes, no default eager loads. */
2365
- newModelQuery(): Builder<this>;
2370
+ compileGroupLimit(query: Builder<unknown>): Sql;
2371
+ /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
2372
+ compileComponents(query: Builder<unknown>): Sql;
2373
+ compileOrders(query: Builder<unknown>): Sql | undefined;
2374
+ compileWheres(wheres: readonly Where[], keyword?: 'where' | 'on'): Sql | undefined;
2375
+ compileWhere(where: Where): Sql;
2366
2376
  /**
2367
- * Inserts the model, or updates its dirty attributes. Only changed columns are written; an unchanged model
2368
- * runs no query at all. Returns false when a saving/creating/updating listener cancels.
2377
+ * whereDate(), whereTime(), whereDay(), whereMonth() and whereYear() per driver, as Laravel 12's grammars: MySQL's
2378
+ * date()/time()/day()/month()/year(), Postgres' ::date, ::time and extract(), SQLite's strftime() compared as text.
2369
2379
  */
2370
- save(): Promise<boolean>;
2371
- /**
2372
- * Laravel's hashed cast (castAttributeAsHashedString()), run when the model is saved because the Hasher is
2373
- * asynchronous: each newly assigned value is hashed before the saving event, so every listener sees the hash, and
2374
- * again just before the write (after the creating or updating event), so a value a listener assigns is hashed too.
2375
- * A value that is already a hash is kept when it matches the configured algorithm and options, and refused
2376
- * otherwise. Only strings and numbers are hashed (null stays null); any other value is refused.
2380
+ compileWhereDate(where: Extract<Where, {
2381
+ type: 'date';
2382
+ }>): Sql;
2383
+ /**
2384
+ * whereLike() per driver, as Laravel 12's grammars: Postgres compares the column as text with ilike (like when
2385
+ * case-sensitive); MySQL uses like (like binary); SQLite uses like, or glob with the pattern translated.
2377
2386
  */
2378
- protected hashPendingAttributes(): Promise<void>;
2379
- /** Fills and saves an existing model. */
2380
- update(attributes?: Row): Promise<boolean>;
2387
+ compileWhereLike(where: Extract<Where, {
2388
+ type: 'like';
2389
+ }>): Sql;
2390
+ compileJoin(joinClause: JoinClause): Sql;
2391
+ compileHavings(havings: readonly Having[]): Sql | undefined;
2392
+ compileLimitOffset(limit: number | undefined, offset: number | undefined): Sql | undefined;
2393
+ compileLock(mode: 'update' | 'share' | undefined): Sql | undefined;
2381
2394
  /**
2382
- * Deletes the model's row, or sets deleted_at with soft deletes. Returns false for a model that isn't saved, or
2383
- * when a deleting listener cancels.
2395
+ * `select count(*) as aggregate …`. Orders, limit and offset are dropped. Grouped or distinct queries, and those with a
2396
+ * `having` (which may name a selected alias, withCount()'s `comments_count`), are wrapped, keeping their columns.
2384
2397
  */
2385
- delete(): Promise<boolean>;
2386
- /** save() without model events. */
2387
- saveQuietly(): Promise<boolean>;
2388
- /** delete() without model events. */
2389
- deleteQuietly(): Promise<boolean>;
2390
- /** True when the model is soft deleted. Only for models with `softDeletes = true`. */
2391
- trashed(): boolean;
2392
- /** Clears deleted_at and saves. Fires restoring (can cancel) and restored. */
2393
- restore(): Promise<boolean>;
2394
- /** Deletes the row for real, even with soft deletes. Fires forceDeleting (can cancel) and forceDeleted. */
2395
- forceDelete(): Promise<boolean>;
2396
- isForceDeleting(): boolean;
2397
- getQualifiedDeletedAtColumn(): string;
2398
- private assertSoftDeletes;
2399
- /** Reloads the attributes and the loaded relations from the database (including a soft-deleted row). */
2400
- refresh(): Promise<this>;
2401
- /** A fresh copy from the database, or undefined when the row is gone. */
2402
- fresh(): Promise<this | undefined>;
2403
- /** Updates updated_at (and saves). */
2404
- touch(): Promise<boolean>;
2405
- /** column = column + amount in the database, mirrored on the model without marking it dirty. */
2406
- increment(column: string, amount?: number, extra?: Row): Promise<number>;
2407
- decrement(column: string, amount?: number, extra?: Row): Promise<number>;
2408
- /** Same table, connection and key. */
2409
- is(other: Model | null | undefined): boolean;
2410
- isNot(other: Model | null | undefined): boolean;
2411
- /** The current time, to the second (the storage precision). */
2412
- freshTimestamp(): Date;
2413
- updateTimestamps(): void;
2414
- protected performInsert(query: Builder<this>): Promise<boolean>;
2415
- protected performUpdate(query: Builder<this>): Promise<boolean>;
2416
- protected finishSave(): Promise<void>;
2417
- protected performDeleteOnModel(): Promise<void>;
2418
- /** deleted_at (and updated_at) = now, on this row only. The model still exists, as a trashed model. */
2419
- protected runSoftDelete(): Promise<void>;
2420
- /** where key = the key the row was loaded with (the original, in case the key itself changed). */
2421
- protected setKeysForSaveQuery(query: Builder<this>): Builder<this>;
2422
- protected incrementOrDecrement(column: string, amount: number, extra: Row): Promise<number>;
2398
+ compileAggregate(query: Builder<unknown>, fn: string, column: string | Expression): Sql;
2399
+ compileExists(query: Builder<unknown>): Sql;
2400
+ compileInsert(query: Builder<unknown>, rows: readonly Row[]): Sql;
2401
+ compileInsertOrIgnore(query: Builder<unknown>, rows: readonly Row[]): Sql;
2402
+ /** `into "table" ("a", "b") values (?, ?), (?, ?)`. Columns are the union of every row's keys; a missing key binds null. */
2403
+ compileInsertBody(query: Builder<unknown>, rows: readonly Row[]): Sql;
2404
+ compileInsertGetId(query: Builder<unknown>, row: Row, keyName: string): Sql;
2405
+ compileUpsert(query: Builder<unknown>, rows: readonly Row[], uniqueBy: readonly string[], update: readonly string[]): Sql;
2406
+ compileUpdate(query: Builder<unknown>, values: Row): Sql;
2407
+ compileDelete(query: Builder<unknown>): Sql;
2408
+ compileTruncate(query: Builder<unknown>): Sql[];
2409
+ compileRandom(): Expression;
2410
+ private assertSimpleMutation;
2411
+ private mysqlOrderAndLimit;
2412
+ }
2413
+
2414
+ type WhereBoolean = 'and' | 'or';
2415
+ type Direction = 'asc' | 'desc';
2416
+ type ColumnRef = string | Expression;
2417
+ type Where = {
2418
+ type: 'basic';
2419
+ column: ColumnRef | Builder<unknown>;
2420
+ operator: string;
2421
+ value: unknown;
2422
+ boolean: WhereBoolean;
2423
+ } | {
2424
+ type: 'in';
2425
+ column: ColumnRef;
2426
+ values: readonly unknown[] | Builder<unknown>;
2427
+ not: boolean;
2428
+ boolean: WhereBoolean;
2429
+ } | {
2430
+ type: 'null';
2431
+ column: ColumnRef;
2432
+ not: boolean;
2433
+ boolean: WhereBoolean;
2434
+ } | {
2435
+ type: 'between';
2436
+ column: ColumnRef;
2437
+ values: readonly [unknown, unknown];
2438
+ not: boolean;
2439
+ boolean: WhereBoolean;
2440
+ } | {
2441
+ type: 'like';
2442
+ column: ColumnRef;
2443
+ value: string;
2444
+ caseSensitive: boolean;
2445
+ not: boolean;
2446
+ boolean: WhereBoolean;
2447
+ } | {
2448
+ type: 'column';
2449
+ first: ColumnRef;
2450
+ operator: string;
2451
+ second: ColumnRef;
2452
+ boolean: WhereBoolean;
2453
+ } | {
2454
+ type: 'nested';
2455
+ query: Builder<unknown>;
2456
+ not: boolean;
2457
+ boolean: WhereBoolean;
2458
+ } | {
2459
+ type: 'exists';
2460
+ query: Builder<unknown>;
2461
+ not: boolean;
2462
+ boolean: WhereBoolean;
2463
+ } | {
2464
+ type: 'raw';
2465
+ sql: string;
2466
+ bindings: readonly unknown[];
2467
+ boolean: WhereBoolean;
2468
+ } | {
2469
+ type: 'date';
2470
+ part: DatePart;
2471
+ column: ColumnRef;
2472
+ operator: string;
2473
+ value: unknown;
2474
+ boolean: WhereBoolean;
2475
+ };
2476
+ /** The part of a date or time column a date where clause compares (whereDate() → 'date', whereYear() → 'year', …). */
2477
+ type DatePart = 'date' | 'time' | 'day' | 'month' | 'year';
2478
+ /** What a date where clause compares with: a Date (read in UTC), a string, a number, or DB.raw(). */
2479
+ type DateWhereValue = Date | string | number | Expression;
2480
+ /** whereDate('published_at', '2026-01-05') or whereDate('published_at', '>=', new Date()). */
2481
+ type DateWhereArgs = [value: DateWhereValue] | [operator: string, value: DateWhereValue];
2482
+ type Having = {
2483
+ column: ColumnRef;
2484
+ operator: string;
2485
+ value: unknown;
2486
+ boolean: WhereBoolean;
2487
+ } | {
2488
+ raw: Expression;
2489
+ boolean: WhereBoolean;
2490
+ };
2491
+ type Order = {
2492
+ column: ColumnRef;
2493
+ direction: Direction;
2494
+ } | {
2495
+ raw: Expression;
2496
+ };
2497
+ /** A column, an expression, or `(subquery) as alias` (`exists (subquery) as alias` with exists). */
2498
+ type SelectColumn = ColumnRef | {
2499
+ query: Builder<unknown>;
2500
+ as: string;
2501
+ exists?: boolean;
2502
+ };
2503
+ type NestedCallback<Q> = (query: Q) => unknown;
2504
+ /** The value when()'s callback receives: the condition's type without its falsy members. */
2505
+ type Truthy<V> = Exclude<V, false | 0 | 0n | '' | null | undefined>;
2506
+ /** The key a selected column comes back under: 'users.name' → 'name', 'name as n' → 'n'. */
2507
+ declare function columnKey(column: string): string;
2508
+ /**
2509
+ * Laravel's query builder: DB.table('users').where('votes', '>', 100).get().
2510
+ * Implements the QueryBuilder contract other components use (Queue, Cache, Session, Validation).
2511
+ */
2512
+ declare class Builder<T = Row> implements QueryBuilder<T> {
2513
+ readonly connection: Connection;
2514
+ readonly grammar: Grammar;
2515
+ columns: SelectColumn[];
2516
+ distinctRows: boolean;
2517
+ fromTable: string | Expression | undefined;
2518
+ joins: JoinClause[];
2519
+ wheres: Where[];
2520
+ groups: ColumnRef[];
2521
+ havings: Having[];
2522
+ orders: Order[];
2523
+ limitValue: number | undefined;
2524
+ offsetValue: number | undefined;
2525
+ /** A limit and offset per value of `column` (each parent of an eager load), compiled as a window (limitPerGroup()). */
2526
+ groupLimit: {
2527
+ column: string;
2528
+ limit: number | undefined;
2529
+ offset: number | undefined;
2530
+ } | undefined;
2531
+ lockMode: 'update' | 'share' | undefined;
2532
+ constructor(connection: Connection, table?: string | Expression);
2533
+ from(table: string | Expression): this;
2534
+ select(...columns: Array<ColumnRef | ColumnRef[]>): this;
2535
+ addSelect(...columns: Array<ColumnRef | ColumnRef[]>): this;
2536
+ selectRaw(expression: string, bindings?: readonly unknown[]): this;
2537
+ /** Adds `(subquery) as alias` to the select list. */
2538
+ selectSub(query: Builder<unknown>, as: string): this;
2539
+ distinct(): this;
2540
+ where(column: ColumnRef, value: unknown): this;
2541
+ where(column: ColumnRef, operator: Operator | string, value: unknown): this;
2542
+ where(conditions: Row): this;
2543
+ where(callback: NestedCallback<Builder<T>>): this;
2544
+ orWhere(column: ColumnRef, value: unknown): this;
2545
+ orWhere(column: ColumnRef, operator: Operator | string, value: unknown): this;
2546
+ orWhere(conditions: Row): this;
2547
+ orWhere(callback: NestedCallback<Builder<T>>): this;
2548
+ /** where not (…): whereNot(q => q.where('a', 1).orWhere('b', 2)). */
2549
+ whereNot(callback: NestedCallback<Builder<T>>): this;
2550
+ orWhereNot(callback: NestedCallback<Builder<T>>): this;
2551
+ whereIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this;
2552
+ orWhereIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this;
2553
+ whereNotIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this;
2554
+ orWhereNotIn(column: ColumnRef, values: readonly unknown[] | Builder<unknown>): this;
2555
+ whereNull(columns: ColumnRef | ColumnRef[]): this;
2556
+ orWhereNull(column: ColumnRef): this;
2557
+ whereNotNull(columns: ColumnRef | ColumnRef[]): this;
2558
+ orWhereNotNull(column: ColumnRef): this;
2559
+ whereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
2560
+ orWhereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
2561
+ whereNotBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
2562
+ /** Compares the date part of a column: whereDate('published_at', '2026-01-05'), whereDate('published_at', '<', new Date()). */
2563
+ whereDate(column: ColumnRef, ...args: DateWhereArgs): this;
2564
+ orWhereDate(column: ColumnRef, ...args: DateWhereArgs): this;
2565
+ /** Compares the time of day: whereTime('published_at', '>=', '09:00:00'). */
2566
+ whereTime(column: ColumnRef, ...args: DateWhereArgs): this;
2567
+ orWhereTime(column: ColumnRef, ...args: DateWhereArgs): this;
2568
+ /** Compares the day of the month: whereDay('published_at', 5). */
2569
+ whereDay(column: ColumnRef, ...args: DateWhereArgs): this;
2570
+ orWhereDay(column: ColumnRef, ...args: DateWhereArgs): this;
2571
+ /** Compares the month: whereMonth('published_at', 12). */
2572
+ whereMonth(column: ColumnRef, ...args: DateWhereArgs): this;
2573
+ orWhereMonth(column: ColumnRef, ...args: DateWhereArgs): this;
2574
+ /** Compares the year: whereYear('published_at', '>=', 2026). */
2575
+ whereYear(column: ColumnRef, ...args: DateWhereArgs): this;
2576
+ orWhereYear(column: ColumnRef, ...args: DateWhereArgs): this;
2423
2577
  /**
2424
- * Dispatches 'eloquent.<event>: <Class>' with the model as payload. Halting events return false when a listener
2425
- * returned false. A no-op without an EventDispatcher binding, or inside withoutEvents().
2578
+ * Laravel's whereLike(): the value is the pattern, `%` and `_` included (`whereLike('title', `%${term}%`)`).
2579
+ * Case-insensitive unless caseSensitive: ilike on Postgres, like on MySQL and SQLite (their like already ignores
2580
+ * case: MySQL through the column's collation, SQLite for ASCII letters). Case-sensitive is like on Postgres,
2581
+ * like binary on MySQL and glob on SQLite.
2426
2582
  */
2427
- fireModelEvent(event: ModelEvent, halt?: boolean): Promise<boolean>;
2428
- /** Whether any listener is registered for one of this model's events (retrieved is skipped when none is). */
2429
- hasModelListeners(event: ModelEvent): boolean;
2583
+ whereLike(column: ColumnRef, value: string, caseSensitive?: boolean, boolean?: WhereBoolean, not?: boolean): this;
2584
+ orWhereLike(column: ColumnRef, value: string, caseSensitive?: boolean): this;
2585
+ whereNotLike(column: ColumnRef, value: string, caseSensitive?: boolean, boolean?: WhereBoolean): this;
2586
+ orWhereNotLike(column: ColumnRef, value: string, caseSensitive?: boolean): this;
2587
+ /** Compares two columns: whereColumn('updated_at', '>', 'created_at'). */
2588
+ whereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef, boolean?: WhereBoolean): this;
2589
+ orWhereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef): this;
2590
+ whereRaw(sql: string, bindings?: readonly unknown[], boolean?: WhereBoolean): this;
2591
+ orWhereRaw(sql: string, bindings?: readonly unknown[]): this;
2592
+ whereExists(query: Builder<unknown> | NestedCallback<Builder<Row>>, boolean?: WhereBoolean, not?: boolean): this;
2593
+ orWhereExists(query: Builder<unknown> | NestedCallback<Builder<Row>>): this;
2594
+ whereNotExists(query: Builder<unknown> | NestedCallback<Builder<Row>>): this;
2595
+ /** `(select …) <operator> value`: used by has('comments', '>=', 3). */
2596
+ whereSub(query: Builder<unknown>, operator: string, value: unknown, boolean?: WhereBoolean): this;
2597
+ /** Appends another builder's where clauses as one nested group. */
2598
+ addNestedWhereQuery(query: Builder<unknown>, boolean?: WhereBoolean, not?: boolean): this;
2599
+ join(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef, type?: JoinType): this;
2600
+ leftJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this;
2601
+ rightJoin(table: string | Expression, first: ColumnRef | ((join: JoinClause) => unknown), operator?: string, second?: ColumnRef): this;
2602
+ crossJoin(table: string | Expression): this;
2603
+ groupBy(...columns: ColumnRef[]): this;
2604
+ having(column: ColumnRef, operatorOrValue: unknown, value?: unknown, boolean?: WhereBoolean): this;
2605
+ havingRaw(sql: string, bindings?: readonly unknown[], boolean?: WhereBoolean): this;
2606
+ orderBy(column: ColumnRef, direction?: Direction | Uppercase<Direction>): this;
2607
+ orderByDesc(column: ColumnRef): this;
2608
+ latest(column?: ColumnRef): this;
2609
+ oldest(column?: ColumnRef): this;
2610
+ inRandomOrder(): this;
2611
+ orderByRaw(sql: string, bindings?: readonly unknown[]): this;
2612
+ /** Removes existing orders, optionally adding a new one. */
2613
+ reorder(column?: ColumnRef, direction?: Direction): this;
2614
+ limit(count: number): this;
2615
+ take(count: number): this;
2616
+ offset(count: number): this;
2617
+ skip(count: number): this;
2618
+ forPage(page: number, perPage?: number): this;
2619
+ lockForUpdate(): this;
2620
+ sharedLock(): this;
2430
2621
  /**
2431
- * One related row holds this model's key: user.profile() → hasOne(Profile) (profiles.user_id = users.id).
2432
- * @param foreignKey on the related table (default: this model's foreign key, e.g. user_id)
2433
- * @param localKey on this model (default: the primary key)
2622
+ * Laravel's when(): callback(query, value) runs when the value is truthy, otherwise(query, value) when it is falsy.
2623
+ * A function value is called with the query first and its result is the value. Truthiness is JavaScript's, so `'0'`
2624
+ * and `[]` are truthy: a `?active=0` filter applies, where Laravel would skip it. Returns the query; what the
2625
+ * callbacks return is ignored.
2626
+ *
2627
+ * @example
2628
+ * Post.query().when(request.query('q'), (query, q) => query.whereLike('title', `%${q}%`))
2434
2629
  */
2435
- hasOne<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasOne<InstanceType<C>, this> & Scopes<C>;
2436
- /** Many related rows hold this model's key: post.comments() → hasMany(Comment) (comments.post_id = posts.id). */
2437
- hasMany<C extends typeof Model>(related: C, foreignKey?: string, localKey?: string): HasMany<InstanceType<C>, this> & Scopes<C>;
2630
+ when<V>(value: (query: this) => V, callback: (query: this, value: Truthy<V>) => unknown, otherwise?: (query: this, value: V) => unknown): this;
2631
+ when<V>(value: V, callback: (query: this, value: Truthy<V>) => unknown, otherwise?: (query: this, value: V) => unknown): this;
2632
+ /** Laravel's unless(): when() with the condition reversed. callback(query, value) runs when the value is falsy. */
2633
+ unless<V>(value: (query: this) => V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: Truthy<V>) => unknown): this;
2634
+ unless<V>(value: V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: Truthy<V>) => unknown): this;
2635
+ tap(callback: (query: this) => unknown): this;
2636
+ get(): Promise<Collection<T>>;
2637
+ /** The collection get() and chunk() hand out (Eloquent's builder makes the model's collection). */
2638
+ protected newCollection(items: T[]): Collection<T>;
2639
+ /** The raw rows, without a Collection around them. */
2640
+ runSelect(): Promise<T[]>;
2438
2641
  /**
2439
- * This model holds the related model's key: post.author() → belongsTo(User, 'user_id').
2440
- * @param foreignKey on this model (default: the related model's foreign key, e.g. user_id)
2441
- * @param ownerKey on the related model (default: its primary key)
2442
- * @param relation the loaded-relation name associate() sets (default: the resolved name, else the class in camelCase)
2642
+ * @internal Eager loading (Laravel 11's groupLimit()): the limit and offset set so far apply to each value of `column`,
2643
+ * the parent's key, instead of to the whole query. Compiled as row_number() over (partition by …).
2443
2644
  */
2444
- belongsTo<C extends typeof Model>(related: C, foreignKey?: string, ownerKey?: string, relation?: string): BelongsTo<InstanceType<C>, this> & Scopes<C>;
2645
+ limitPerGroup(column: string): this;
2646
+ first(): Promise<T | undefined>;
2647
+ find(id: unknown, keyName?: string): Promise<T | undefined>;
2648
+ value<V = unknown>(column: string): Promise<V | undefined>;
2649
+ pluck<V = unknown>(column: string): Promise<Collection<V>>;
2650
+ count(column?: ColumnRef): Promise<number>;
2651
+ min<V = unknown>(column: ColumnRef): Promise<V | undefined>;
2652
+ max<V = unknown>(column: ColumnRef): Promise<V | undefined>;
2653
+ sum(column: ColumnRef): Promise<number>;
2654
+ avg(column: ColumnRef): Promise<number | undefined>;
2655
+ aggregate(fn: 'count' | 'min' | 'max' | 'sum' | 'avg', column: ColumnRef): Promise<unknown>;
2656
+ exists(): Promise<boolean>;
2657
+ doesntExist(): Promise<boolean>;
2658
+ insert(values: Row | Row[]): Promise<void>;
2659
+ /** Inserts one row and returns its auto-increment id. */
2660
+ insertGetId(values: Row, keyName?: string): Promise<number | string>;
2661
+ /** Inserts rows, skipping the ones that violate a unique constraint. Returns how many were inserted. */
2662
+ insertOrIgnore(values: Row | Row[]): Promise<number>;
2663
+ update(values: Row): Promise<number>;
2664
+ /** Updates the row matching attributes, or inserts attributes + values. */
2665
+ updateOrInsert(attributes: Row, values?: Row): Promise<boolean>;
2445
2666
  /**
2446
- * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).
2447
- * @param table default: the two singular snake names in alphabetical order (post_tag)
2448
- * @param foreignPivotKey the pivot column pointing at this model (default: post_id)
2449
- * @param relatedPivotKey the pivot column pointing at the related model (default: tag_id)
2667
+ * Inserts rows, updating `update` (default: every inserted column except uniqueBy) when a row already exists.
2668
+ * uniqueBy must be a primary key or unique index (Postgres and SQLite need it for ON CONFLICT).
2450
2669
  */
2451
- belongsToMany<C extends typeof Model>(related: C, table?: string, foreignPivotKey?: string, relatedPivotKey?: string, parentKey?: string, relatedKey?: string): BelongsToMany<InstanceType<C>, this> & Scopes<C>;
2670
+ upsert(values: Row | Row[], uniqueBy: string[], update?: string[]): Promise<number>;
2671
+ increment(column: string, amount?: number, extra?: Row): Promise<number>;
2672
+ decrement(column: string, amount?: number, extra?: Row): Promise<number>;
2673
+ delete(id?: unknown): Promise<number>;
2674
+ truncate(): Promise<void>;
2452
2675
  /**
2453
- * Related rows through an intermediate model: country.posts() → hasManyThrough(Post, User).
2454
- * @param firstKey on the through table (default: this model's foreign key, country_id)
2455
- * @param secondKey on the related table (default: the through model's foreign key, user_id)
2676
+ * Paginates with a total count (two queries: count, then the page). The page comes from ?page= on the current
2677
+ * request unless given: DB.table('users').orderBy('id').paginate(15).
2456
2678
  */
2457
- hasManyThrough<C extends typeof Model, T extends typeof Model>(related: C, through: T, firstKey?: string, secondKey?: string, localKey?: string, secondLocalKey?: string): HasManyThrough<InstanceType<C>, this, InstanceType<T>> & Scopes<C>;
2458
- /** A polymorphic one-to-one: user.image() → morphOne(Image, 'imageable') (images.imageable_id/_type). */
2459
- morphOne<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphOne<InstanceType<C>, this> & Scopes<C>;
2460
- /** A polymorphic one-to-many: post.comments() → morphMany(Comment, 'commentable'). */
2461
- morphMany<C extends typeof Model>(related: C, name: string, type?: string, id?: string, localKey?: string): MorphMany<InstanceType<C>, this> & Scopes<C>;
2679
+ paginate(perPage?: number, columns?: ColumnRef[], pageName?: string, page?: number): Promise<LengthAwarePaginator<T>>;
2680
+ /** Paginates without a count: fetches perPage + 1 rows to know whether there is a next page. */
2681
+ simplePaginate(perPage?: number, columns?: ColumnRef[], pageName?: string, page?: number): Promise<Paginator<T>>;
2462
2682
  /**
2463
- * The inverse of morphOne/morphMany: comment.commentable() → morphTo('commentable'). The name is required
2464
- * (Laravel reads it from the calling method, which JavaScript can't do reliably).
2683
+ * Paginates by the ordered columns' values instead of an offset. Needs an orderBy (Eloquent adds the primary key);
2684
+ * the cursor comes from ?cursor= on the current request unless given.
2465
2685
  */
2466
- morphTo<R extends Model = Model>(name: string, type?: string, id?: string, ownerKey?: string): MorphTo<R, this>;
2467
- /** The value stored in *_type columns for this model: its morph map alias, or its class name. */
2468
- getMorphClass(): string;
2469
- /** The pivot row of a model loaded through belongsToMany (tag.pivot.getAttribute('created_at')). */
2470
- get pivot(): Model | undefined;
2471
- /** A related model instance on this model's connection when it has none of its own. */
2472
- protected newRelatedInstance<C extends typeof Model>(related: C): InstanceType<C>;
2473
- /** Whether the model has a relation method called `name` (Laravel's isRelation()). */
2474
- isRelation(name: string): boolean;
2475
- /** Calls the relation method `name` (post.comments()) and checks that it returns a relation. */
2476
- getRelationInstance(name: string): Relation;
2686
+ cursorPaginate(perPage?: number, columns?: ColumnRef[], cursorName?: string, cursor?: Cursor | string): Promise<CursorPaginator<T>>;
2477
2687
  /**
2478
- * A loaded relation, typed from the relation method: post.getRelation('author') is User | null,
2479
- * post.getRelation('comments') is EloquentCollection<Comment>. Throws RelationNotLoadedError when it isn't loaded
2480
- * (JavaScript can't lazy-load synchronously: use with(), load() or post.comments().get()).
2688
+ * Runs the query page by page and passes each chunk to callback. Return false to stop. Needs an orderBy, so that
2689
+ * pages don't overlap. Don't update the ordered column inside the callback; use chunkById() for that.
2481
2690
  */
2482
- getRelation<K extends RelationNames<this>>(name: K): RelationValue<this, K>;
2483
- /** Eager loads relations onto this model: await post.load('comments.author'). */
2484
- load(...relations: EagerLoadSpec[]): Promise<this>;
2485
- /** Loads only the relations that aren't loaded yet (nested paths are followed into loaded relations). */
2486
- loadMissing(...relations: string[]): Promise<this>;
2487
- /** Loads <relation>_count attributes: await post.loadCount('comments'). */
2488
- loadCount(...relations: EagerLoadSpec[]): Promise<this>;
2489
- /** Loads an aggregate of a relation as an attribute (Laravel's loadAggregate()): see withAggregate(). */
2490
- loadAggregate(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): Promise<this>;
2491
- /** Loads <relation>_sum_<column>: await user.loadSum('orders', 'price'). */
2492
- loadSum(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
2493
- loadAvg(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
2494
- loadMin(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
2495
- loadMax(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
2496
- /** Loads a boolean <relation>_exists. */
2497
- loadExists(...relations: EagerLoadSpec[]): Promise<this>;
2691
+ chunk(count: number, callback: (results: Collection<T>, page: number) => unknown): Promise<boolean>;
2692
+ /** Chunks by comparing the key (where id > last id), so it is safe to update or delete rows inside the callback. */
2693
+ chunkById(count: number, callback: (results: Collection<T>, page: number) => unknown, column?: string, alias?: string): Promise<boolean>;
2694
+ /** Calls callback for every row, fetching `count` rows per query. Return false to stop. */
2695
+ each(callback: (item: T, index: number) => unknown, count?: number): Promise<boolean>;
2696
+ /** A LazyCollection that runs one query per chunk as it is iterated: for await (const user of query.lazy()). */
2697
+ lazy(chunkSize?: number): LazyCollection<T>;
2698
+ /** Like lazy(), but pages by key, so rows can be updated while iterating. */
2699
+ lazyById(chunkSize?: number, column?: string, alias?: string): LazyCollection<T>;
2700
+ /** where column > lastId order by column limit perPage (existing orders on the column are replaced). */
2701
+ forPageAfterId(perPage?: number, lastId?: unknown, column?: string): this;
2702
+ /** chunk() and lazy() need a stable order. Eloquent orders by the primary key instead of throwing. */
2703
+ protected enforceOrderBy(): void;
2704
+ /** The key chunkById()/lazyById() use by default. Eloquent uses the model's key. */
2705
+ protected defaultKeyName(): string;
2706
+ /** The page size when none is given. Eloquent uses the model's perPage. */
2707
+ protected defaultPerPage(): number;
2708
+ /** Laravel's get($columns): only applies when no columns were selected yet. */
2709
+ private withColumns;
2710
+ /** The column orders cursor pagination compares on; reversed (in the query too) when paging backwards. */
2711
+ private ordersForCursor;
2712
+ /** (a > ?) or (a = ? and (b > ? or (b = ? and …))), Laravel's cursor conditions. */
2713
+ private whereCursor;
2714
+ /** The compiled SQL (placeholders included), for debugging and tests. */
2715
+ toSql(): string;
2716
+ getBindings(): unknown[];
2717
+ clone(): Builder<T>;
2718
+ /** A fresh builder on the same connection and table (for nested where groups). */
2719
+ newQuery(): Builder<Row>;
2720
+ requireTable(): string | Expression;
2721
+ private subQuery;
2722
+ private addNested;
2723
+ private addWhere;
2724
+ /** Laravel's addDateBasedWhere(): one value means '='; the operator is checked against the whitelist. */
2725
+ private addDateBasedWhere;
2726
+ private pushNull;
2727
+ }
2728
+ type JoinType = 'inner' | 'left' | 'right' | 'cross';
2729
+ /** The `on …` part of a join. `where()` on a join binds a value; `on()` compares columns. */
2730
+ declare class JoinClause extends Builder<Row> {
2731
+ readonly joinType: JoinType;
2732
+ readonly table: string | Expression;
2733
+ constructor(parent: Builder<unknown>, joinType: JoinType, table: string | Expression);
2734
+ on(first: ColumnRef, operator: string, second?: ColumnRef, boolean?: WhereBoolean): this;
2735
+ orOn(first: ColumnRef, operator: string, second?: ColumnRef): this;
2736
+ }
2737
+
2738
+ /** Laravel's storage format ('Y-m-d H:i:s'), in UTC. */
2739
+ declare function formatDateTime(date: Date): string;
2740
+ declare function formatDate(date: Date): string;
2741
+ /**
2742
+ * Parses a stored date/time as UTC. Accepts Dates, epoch milliseconds, 'Y-m-d', 'Y-m-d H:i:s' and ISO strings
2743
+ * (the last two with or without a zone suffix; a missing zone means UTC).
2744
+ */
2745
+ declare function parseDateTime(value: unknown): Date;
2746
+ /** Normalizes one binding for the driver: booleans, dates, JSON and undefined. */
2747
+ declare function prepareValue(value: unknown, driver: DriverName): unknown;
2748
+
2749
+ /** `config('database')`, in Laravel's config/database.php shape. */
2750
+ interface DatabaseConfig {
2751
+ default: string;
2752
+ connections: Record<string, ConnectionConfig>;
2753
+ /** Laravel 11: { table: 'migrations' }. A plain string (older Laravel) is accepted too. */
2754
+ migrations?: {
2755
+ table?: string;
2756
+ } | string;
2757
+ }
2758
+ /**
2759
+ * The DatabaseManager contract: named connections from config('database'), created on first use and cached.
2760
+ * Everything a connection does is also available here and runs on the default connection, as with Laravel's DB facade.
2761
+ * Named DatabaseManagerImpl so it never shadows the DatabaseManager token when both are re-exported.
2762
+ */
2763
+ declare class DatabaseManagerImpl implements DatabaseManager {
2764
+ private readonly config;
2765
+ private readonly connections;
2766
+ private defaultName;
2767
+ /** usingConnection()'s name, for its own async context only: requests running beside it keep theirs. */
2768
+ private readonly using;
2769
+ /** Pass the config, or a function that reads it (the provider reads config('database') lazily). */
2770
+ constructor(config: DatabaseConfig | (() => DatabaseConfig));
2771
+ private settings;
2772
+ /** A connection by name (default: config('database.default')). */
2773
+ connection(name?: string): Connection;
2774
+ getDefaultConnection(): string;
2775
+ /** Overrides config('database.default'); undefined clears the override. */
2776
+ setDefaultConnection(name: string | undefined): void;
2498
2777
  /**
2499
- * The collection queries of this model return (Laravel's newCollection()): an EloquentCollection. Override it to
2500
- * return a subclass with your own methods.
2778
+ * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), for the callback's own async
2779
+ * context only: other requests running meanwhile keep their default. Without a name, just runs it.
2501
2780
  */
2502
- newCollection<T extends Model>(this: T, models?: T[]): EloquentCollection<T>;
2503
- /** Stores a loaded relation (eager loading and load() use this). */
2504
- setRelation(name: string, value: unknown): this;
2505
- relationLoaded(name: string): boolean;
2506
- unsetRelation(name: string): this;
2507
- getRelations(): Record<string, unknown>;
2508
- getHidden(): string[];
2509
- setHidden(hidden: string[]): this;
2510
- getVisible(): string[];
2511
- setVisible(visible: string[]): this;
2512
- /** Hides attributes for this instance only. */
2513
- makeHidden(...attributes: Array<string | string[]>): this;
2514
- /** Un-hides attributes for this instance only. */
2515
- makeVisible(...attributes: Array<string | string[]>): this;
2516
- getAppends(): string[];
2517
- setAppends(appends: string[]): this;
2518
- /** Adds accessor-only attributes to the serialized form of this instance. */
2519
- append(...attributes: Array<string | string[]>): this;
2781
+ usingConnection<T>(name: string | undefined, callback: () => Promise<T>): Promise<T>;
2782
+ /** The connections opened so far. */
2783
+ getConnections(): Record<string, Connection>;
2784
+ /** The migrations table name (config('database.migrations.table'), default 'migrations'). */
2785
+ migrationsTable(): string;
2786
+ /** Closes a connection's pool and forgets it; the next connection(name) opens a new one. */
2787
+ disconnect(name?: string): Promise<void>;
2788
+ /** Laravel's purge(): the same as disconnect() here. */
2789
+ purge(name?: string): Promise<void>;
2790
+ /** Closes every open connection (app shutdown, the end of a test). */
2791
+ disconnectAll(): Promise<void>;
2792
+ /** The default connection's schema builder; Schema.connection(name) switches connections through this manager. */
2793
+ getSchemaBuilder(): SchemaBuilder;
2794
+ /** A raw SQL fragment: DB.raw('count(*) as total'). */
2795
+ raw(value: string, bindings?: readonly unknown[]): Expression;
2796
+ getName(): string;
2797
+ getDriverName(): DriverName;
2798
+ kysely(): ReturnType<Connection['kysely']>;
2799
+ table<T = Row>(table: string | Expression): Builder<T>;
2800
+ query<T = Row>(): Builder<T>;
2801
+ select<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T[]>;
2802
+ /** The first row of a raw select, or undefined. */
2803
+ selectOne<T = Row>(query: string, bindings?: readonly unknown[]): Promise<T | undefined>;
2804
+ /** Raw insert. Returns true, like Laravel's DB::insert(). */
2805
+ insert(query: string, bindings?: readonly unknown[]): Promise<boolean>;
2806
+ /** Raw update; returns the number of affected rows. */
2807
+ update(query: string, bindings?: readonly unknown[]): Promise<number>;
2808
+ /** Raw delete; returns the number of affected rows. */
2809
+ delete(query: string, bindings?: readonly unknown[]): Promise<number>;
2810
+ statement(query: string, bindings?: readonly unknown[]): Promise<void>;
2811
+ affectingStatement(query: string, bindings?: readonly unknown[]): Promise<number>;
2812
+ transaction<R>(fn: (connection: Connection) => Promise<R>): Promise<R>;
2813
+ beginTransaction(): Promise<void>;
2520
2814
  /**
2521
- * Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones.
2522
- * A model met again while its own toArray() runs (a child chaperone() pointed back at it) gives its attributes only.
2815
+ * Laravel's DB::afterCommit(): waits for the transaction(fn) open in this async context, on the default connection
2816
+ * first, then on any other opened one; runs at once outside one. It opens no connection: one with a transaction is
2817
+ * open already.
2523
2818
  */
2524
- toArray(): Row;
2525
- toJSON(): Row;
2526
- attributesToArray(): Row;
2527
- /** Loaded relations under their snake_case names: a model → its array, a collection → an array of arrays. */
2528
- relationsToArray(): Row;
2529
- protected serializeValue(value: unknown): unknown;
2530
- private isArrayableKey;
2531
- private arrayable;
2532
- }
2533
- /** Eager loads relations onto models you already have (Laravel's $collection->load()). */
2534
- declare function loadRelations<M extends Model>(models: Iterable<M>, ...relations: EagerLoadSpec[]): Promise<M[]>;
2535
- /** A row of a belongsToMany pivot table, available as related.pivot (unguarded, no key, no timestamps by default). */
2536
- declare class Pivot extends Model {
2537
- protected guarded: string[];
2538
- incrementing: boolean;
2539
- timestamps: boolean;
2819
+ afterCommit(callback: () => unknown, onRollBack?: () => unknown): Promise<void>;
2820
+ commit(): Promise<void>;
2821
+ rollBack(): Promise<void>;
2822
+ transactionLevel(): number;
2823
+ enableQueryLog(): void;
2824
+ disableQueryLog(): void;
2825
+ getQueryLog(): LoggedQuery[];
2826
+ flushQueryLog(): void;
2540
2827
  }
2541
2828
 
2829
+ /**
2830
+ * The DB facade: DB.table('users').get(), DB.transaction(fn), DB.connection('pgsql'), DB.kysely().
2831
+ * DB.raw() works without an application (it only builds an Expression).
2832
+ */
2833
+ declare const DB: _orieljs_support.Facade<DatabaseManagerImpl, {
2834
+ raw: typeof raw;
2835
+ }>;
2836
+ /** The Schema facade's binding: the default connection's SchemaBuilder (DatabaseServiceProvider binds it). */
2837
+ declare const SchemaBuilderToken: Token<SchemaBuilder>;
2838
+ /** The Schema facade: Schema.create('posts', (t) => { … }), Schema.table(…), Schema.dropIfExists(…). */
2839
+ declare const Schema: _orieljs_support.Facade<SchemaBuilder, object>;
2840
+
2542
2841
  declare const DatabaseNotification_base: typeof Model;
2543
2842
  /**
2544
2843
  * Laravel's DatabaseNotification: one row of the `notifications` table, which the database channel writes. A UUID
@@ -2580,9 +2879,9 @@ declare class DatabaseNotification extends DatabaseNotification_base implements
2580
2879
  /** Queries of notifications return a DatabaseNotificationCollection (markAsRead() on all of them). */
2581
2880
  newCollection<T extends Model>(this: T, models?: T[]): EloquentCollection<T>;
2582
2881
  /** `query.read()`: only read notifications. */
2583
- static scopeRead(query: Builder<DatabaseNotification>): Builder<DatabaseNotification>;
2882
+ static scopeRead(query: Builder$1<DatabaseNotification>): Builder$1<DatabaseNotification>;
2584
2883
  /** `query.unread()`: only unread notifications. */
2585
- static scopeUnread(query: Builder<DatabaseNotification>): Builder<DatabaseNotification>;
2884
+ static scopeUnread(query: Builder$1<DatabaseNotification>): Builder$1<DatabaseNotification>;
2586
2885
  }
2587
2886
  /** Laravel's DatabaseNotificationCollection: what `await user.notifications().get()` returns. */
2588
2887
  declare class DatabaseNotificationCollection extends EloquentCollection<DatabaseNotification> {
@@ -2641,7 +2940,7 @@ declare function resolveMorphClass(type: string): typeof Model;
2641
2940
  * Builder.withTrashed()/onlyTrashed()/withoutTrashed() remove or replace it.
2642
2941
  */
2643
2942
  declare class SoftDeletingScope implements Scope {
2644
- apply(builder: Builder<any>, model: Model): void;
2943
+ apply(builder: Builder$1<any>, model: Model): void;
2645
2944
  }
2646
2945
 
2647
2946
  /**
@@ -2968,4 +3267,4 @@ declare class DatabaseServiceProvider extends ServiceProvider {
2968
3267
  private manager;
2969
3268
  }
2970
3269
 
2971
- export { AbstractPaginator, type Attributes, BelongsTo, BelongsToMany, Blueprint, type BlueprintCommand, Builder, type BuiltInCast, type BunDatabase, BunSqliteDatabase, type BunStatement, type CastDefinition, type CastsAttributes, type Column, type ColumnAttributes, ColumnDefinition, type ColumnInfo, type ColumnRef, type ColumnType, Connection, type ConnectionConfig, type CreateMigrationOptions, Cursor, CursorPaginator, type CursorPaginatorOptions, DB, type DatabaseCommandContext, type DatabaseConfig, DatabaseConfigError, DatabaseError, DatabaseManagerImpl, DatabaseNotification, DatabaseNotificationCollection, DatabaseNotificationsRelation, DatabaseServiceProvider, type DatePart, type DateWhereArgs, type DateWhereValue, type Direction, type EagerLoadSpec, EloquentCollection, type EnumLike, Expression, Factory, type FactoryResult, Faker, FakerOverflowError, ForeignIdColumnDefinition, ForeignKeyDefinition, type ForeignKeyInfo, type GlobalScope, Grammar, HasDatabaseNotifications, type HasDatabaseNotificationsModel, type HasFactory, HasMany, HasManyThrough, HasOne, HasOneOrMany, HasUlids, HasUuids, type Having, type IndexInfo, type IndexType, InvalidCastError, JoinClause, type JoinType, LengthAwarePaginator, type LoggedQuery, LogicError, MIGRATION_CREATE_STUB, MIGRATION_STUB, MIGRATION_UPDATE_STUB, MODEL_EVENTS, type Many, MassAssignmentError, Migration, MigrationCreator, type MigrationRecord, MigrationRepository, type MigrationStatus, Migrator, type MigratorOptions, Model, type ModelBuilder, type ModelClass, type ModelConstructor, type ModelEvent, type ModelListener, ModelNotFoundError, ModelRegistry, type MorphConstraint, MorphMany, MorphOne, MorphTo, MySqlSchemaGrammar, OPERATORS, type Order, type PaginationLink, Paginator, type PaginatorOptions, Pivot, type PivotIds, PostgresSchemaGrammar, Builder$1 as QueryBuilder, QueryError, type RawResult, type ReferentialAction, type RegisteredModel, Relation, type RelationConstraint, type RelationNames, RelationNotFoundError, RelationNotLoadedError, type RelationValue, type RollbackOptions, RouteModelResolverImpl, Schema, SchemaBuilder, SchemaBuilderToken, SchemaGrammar, type SchemaStep, type Scope, type ScopeCallback, type ScopeStatic, type Scopes, Seeder, type SeederClass, type SelectColumn, SoftDeletingScope, SqliteSchemaGrammar, type State, type StateContext, type SyncChanges, type TableRebuild, TypeGenerator, type TypeGeneratorOptions, type Where, type WhereArgs, type WhereBoolean, buildQuery, castGet, castSet, columnKey, createDialect, databaseConfigDefaults, discoverFactories, enumValues, fake, formatDate, formatDateTime, generateModelTypes, getMorphAlias, getMorphedModel, guessTable, isBun, isDateCast, isEquivalent, isJsonCast, isTableRebuild, loadRelations, migrationDatePrefix, modelEventName, morphMap, mysqlPoolOptions, openSqlite, parseDateTime, prepareValue, raw, rawWithBindings, registerMigrationCommands, registerModelTypesCommand, resolveMorphClass, runSeeder, serializeDate, usePaginationResolvers };
3270
+ export { AbstractPaginator, type AggregateName, type Attributes, BelongsTo, BelongsToMany, Blueprint, type BlueprintCommand, Builder$1 as Builder, type BuiltInCast, type BunDatabase, BunSqliteDatabase, type BunStatement, type CastDefinition, type CastsAttributes, type Column, type ColumnAttributes, ColumnDefinition, type ColumnInfo, type ColumnRef, type ColumnType, Connection, type ConnectionConfig, type CreateMigrationOptions, Cursor, CursorPaginator, type CursorPaginatorOptions, DB, type DatabaseCommandContext, type DatabaseConfig, DatabaseConfigError, DatabaseError, DatabaseManagerImpl, DatabaseNotification, DatabaseNotificationCollection, DatabaseNotificationsRelation, DatabaseServiceProvider, type DatePart, type DateWhereArgs, type DateWhereValue, type Direction, type EagerLoadName, type EagerLoadSpec, EloquentCollection, type EnumLike, Expression, Factory, type FactoryResult, Faker, FakerOverflowError, ForeignIdColumnDefinition, ForeignKeyDefinition, type ForeignKeyInfo, type GlobalScope, Grammar, HasDatabaseNotifications, type HasDatabaseNotificationsModel, type HasFactory, type HasGeneratedTypes, HasMany, HasManyThrough, HasOne, HasOneOrMany, HasUlids, HasUuids, type Having, type IndexInfo, type IndexType, InvalidCastError, JoinClause, type JoinType, LengthAwarePaginator, type LoadedLeaf, type LoadedTree, type LoggedQuery, LogicError, MIGRATION_CREATE_STUB, MIGRATION_STUB, MIGRATION_UPDATE_STUB, MODEL_EVENTS, type Many, MassAssignmentError, Migration, MigrationCreator, type MigrationRecord, MigrationRepository, type MigrationStatus, Migrator, type MigratorOptions, Model, type ModelBuilder, type ModelClass, type ModelConstructor, type ModelEvent, type ModelKey, type ModelListener, ModelNotFoundError, ModelRegistry, type MorphConstraint, MorphMany, MorphOne, MorphTo, MySqlSchemaGrammar, OPERATORS, type Order, type PageCollection, type PaginationLink, Paginator, type PaginatorOptions, Pivot, type PivotIds, PostgresSchemaGrammar, Builder as QueryBuilder, QueryError, type RawResult, type ReferentialAction, type RegisteredModel, Relation, type RelationConstraint, type RelationNames, RelationNotFoundError, RelationNotLoadedError, type RelationPath, type RelationValue, type RollbackOptions, RouteModelResolverImpl, Schema, SchemaBuilder, SchemaBuilderToken, SchemaGrammar, type SchemaStep, type Scope, type ScopeCallback, type ScopeStatic, type Scopes, Seeder, type SeederClass, type SelectColumn, SoftDeletingScope, SqliteSchemaGrammar, type State, type StateContext, type SyncChanges, type TableRebuild, TypeGenerator, type TypeGeneratorOptions, type Where, type WhereArgs, type WhereBoolean, type WithLoaded, type WritableKey, type WriteAttributes, type WriteValue, buildQuery, castGet, castSet, columnKey, createDialect, databaseConfigDefaults, discoverFactories, enumValues, fake, formatDate, formatDateTime, generateModelTypes, getMorphAlias, getMorphedModel, guessTable, isBun, isDateCast, isEquivalent, isJsonCast, isTableRebuild, loadRelations, migrationDatePrefix, modelEventName, morphMap, mysqlPoolOptions, openSqlite, parseDateTime, prepareValue, raw, rawWithBindings, registerMigrationCommands, registerModelTypesCommand, resolveMorphClass, runSeeder, usePaginationResolvers };