@orieljs/database 0.1.0-alpha.6 → 0.1.0-alpha.8

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,6 +1,6 @@
1
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';
2
2
  import { SqliteDatabase, SqliteStatement, Dialect, RawBuilder, Kysely, CompiledQuery, QueryResult } from 'kysely';
3
- import { Collection, LazyCollection } from '@orieljs/collections';
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
6
 
@@ -154,6 +154,8 @@ interface ColumnAttributes {
154
154
  after?: string;
155
155
  first?: boolean;
156
156
  onUpdate?: Expression;
157
+ /** Set by change(): the column exists and is redefined, not added. */
158
+ change?: boolean;
157
159
  }
158
160
  /** A column in a Blueprint, with Laravel's fluent modifiers: t.string('email').nullable().unique(). */
159
161
  declare class ColumnDefinition {
@@ -179,6 +181,12 @@ declare class ColumnDefinition {
179
181
  first(): this;
180
182
  /** default CURRENT_TIMESTAMP. */
181
183
  useCurrent(): this;
184
+ /**
185
+ * Redefines an existing column (Laravel's change()): t.string('title', 500).nullable().change(). As in Laravel 11+,
186
+ * the column becomes exactly this definition: a modifier it had and that isn't given again (nullable, default,
187
+ * comment, …) is dropped. On SQLite the table is rebuilt.
188
+ */
189
+ change(): this;
182
190
  /** MySQL only: on update CURRENT_TIMESTAMP. */
183
191
  useCurrentOnUpdate(): this;
184
192
  }
@@ -239,8 +247,12 @@ type BlueprintCommand = {
239
247
  from: string;
240
248
  to: string;
241
249
  } | {
242
- name: 'dropPrimary' | 'dropUnique' | 'dropIndex' | 'dropForeign';
250
+ name: 'dropPrimary' | 'dropUnique' | 'dropIndex';
251
+ index: string;
252
+ } | {
253
+ name: 'dropForeign';
243
254
  index: string;
255
+ columns?: string[];
244
256
  } | {
245
257
  name: 'rename';
246
258
  to: string;
@@ -313,6 +325,7 @@ declare class Blueprint {
313
325
  /** By name, or by columns (the conventional {table}_{columns}_unique name). */
314
326
  dropUnique(index: string | string[]): void;
315
327
  dropIndex(index: string | string[]): void;
328
+ /** By name, or by columns (the conventional name; SQLite needs the columns, it doesn't keep foreign key names). */
316
329
  dropForeign(index: string | string[]): void;
317
330
  /** Drops the foreign key on the column, then the column. */
318
331
  dropConstrainedForeignId(column: string): void;
@@ -323,6 +336,10 @@ declare class Blueprint {
323
336
  rename(to: string): void;
324
337
  drop(): void;
325
338
  dropIfExists(): void;
339
+ /** The columns this blueprint adds (not the ones change() redefines). */
340
+ addedColumns(): ColumnDefinition[];
341
+ /** The existing columns change() redefines (on a table being created, every column is added instead). */
342
+ changedColumns(): ColumnDefinition[];
326
343
  /** Laravel's default index name: {table}_{columns}_{type}, lowercased, with - and . replaced by _. */
327
344
  createIndexName(type: IndexType | 'foreign', columns: string[]): string;
328
345
  /** The index commands implied by column modifiers (t.string('email').unique()), in column order. */
@@ -343,6 +360,42 @@ interface ColumnInfo {
343
360
  default: string | null;
344
361
  auto_increment: boolean;
345
362
  }
363
+ /** One index of an existing table, as reported by Schema.getIndexes() (Laravel's shape). */
364
+ interface IndexInfo {
365
+ /** Lower-cased. The primary key is 'primary' on MySQL and on a SQLite rowid table, `{table}_pkey` on Postgres. */
366
+ name: string;
367
+ columns: string[];
368
+ /** The index method ('btree', 'hash', …) on Postgres and MySQL; null on SQLite. */
369
+ type: string | null;
370
+ unique: boolean;
371
+ primary: boolean;
372
+ }
373
+ /** One foreign key of an existing table, as reported by Schema.getForeignKeys() (Laravel's shape). */
374
+ interface ForeignKeyInfo {
375
+ /** The constraint name; null on SQLite, which doesn't keep it. */
376
+ name: string | null;
377
+ columns: string[];
378
+ foreign_schema: string;
379
+ foreign_table: string;
380
+ /** Empty when a SQLite key names only the table (it then points at that table's primary key). */
381
+ foreign_columns: string[];
382
+ /** 'cascade', 'restrict', 'set null', 'set default' or 'no action'. */
383
+ on_update: string;
384
+ on_delete: string;
385
+ }
386
+ /**
387
+ * A step a blueprint can't express as fixed SQL: on SQLite, rebuilding the table from its live definition plus these
388
+ * key commands and changed columns. SchemaBuilder.build() runs it (Schema/SqliteTableRebuild.ts).
389
+ */
390
+ interface TableRebuild {
391
+ readonly kind: 'rebuild';
392
+ readonly table: string;
393
+ readonly commands: BlueprintCommand[];
394
+ readonly changes: ColumnDefinition[];
395
+ }
396
+ /** One step of a compiled blueprint: a statement, or a table rebuild. */
397
+ type SchemaStep = Sql$1 | TableRebuild;
398
+ declare const isTableRebuild: (step: SchemaStep) => step is TableRebuild;
346
399
  /**
347
400
  * Turns a Blueprint into DDL for one driver (Laravel's Schema\Grammars). Identifiers go through sql.id();
348
401
  * default values and comments are quoted literals (sql.lit); only DB.raw() defaults are written as-is.
@@ -352,11 +405,18 @@ declare abstract class SchemaGrammar {
352
405
  abstract readonly driver: DriverName;
353
406
  constructor(config?: Partial<ConnectionConfig>);
354
407
  static for(driver: DriverName, config?: Partial<ConnectionConfig>): SchemaGrammar;
355
- /** Every statement for the blueprint: create/add first, then commands in order, then indexes from column modifiers. */
408
+ /**
409
+ * Every statement for the blueprint: create/add first, then commands in order, then indexes from column modifiers.
410
+ * A blueprint that can only run against the live table (a SQLite rebuild) throws: run it with Schema.table().
411
+ */
356
412
  compile(blueprint: Blueprint): Sql$1[];
413
+ /** compile() with table rebuilds as steps of their own; consecutive rebuilds of one run are merged into one. */
414
+ compileSteps(blueprint: Blueprint): SchemaStep[];
357
415
  protected compileCreate(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql$1;
358
416
  protected compileAdd(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql$1[];
359
- protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): Sql$1[];
417
+ /** Redefines an existing column (change()). */
418
+ protected abstract compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[];
419
+ protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): SchemaStep[];
360
420
  compileRename(from: string, to: string): Sql$1;
361
421
  compileDrop(table: string): Sql$1;
362
422
  compileDropIfExists(table: string): Sql$1;
@@ -383,16 +443,28 @@ declare abstract class SchemaGrammar {
383
443
  abstract compileTables(): Sql$1;
384
444
  abstract compileColumns(table: string): Sql$1;
385
445
  abstract normalizeColumns(rows: Array<Record<string, unknown>>, tableSql?: string): ColumnInfo[];
446
+ abstract compileIndexes(table: string): Sql$1;
447
+ abstract normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[];
448
+ abstract compileForeignKeys(table: string): Sql$1;
449
+ abstract normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[];
386
450
  abstract compileEnableForeignKeyConstraints(): Sql$1;
387
451
  abstract compileDisableForeignKeyConstraints(): Sql$1;
388
452
  }
389
453
  declare class SqliteSchemaGrammar extends SchemaGrammar {
390
454
  readonly driver: "sqlite";
391
- /** SQLite can't add keys to an existing table, so primary and foreign keys go inside create table. */
455
+ /** A new table's primary and foreign keys go inside create table (adding them later rebuilds the table). */
392
456
  protected compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql$1;
393
457
  /** New columns may carry an inline `references` clause (the only foreign key SQLite can add later). */
394
458
  protected compileAdd(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql$1[];
395
- protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): Sql$1[];
459
+ /**
460
+ * SQLite can't add or drop a primary or foreign key on an existing table: those commands rebuild the table (Laravel
461
+ * 11+'s compileAlter), as a step SchemaBuilder.build() runs against the live table.
462
+ */
463
+ protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): SchemaStep[];
464
+ /** SQLite can't alter a column: changing one rebuilds the table with the new definition. */
465
+ protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[];
466
+ /** `foreign key (…) references … on delete …`, a table constraint of a rebuilt table. */
467
+ compileForeignKeyConstraint(foreign: ForeignKeyDefinition): Sql$1;
396
468
  protected compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql$1;
397
469
  protected compileDropUnique(_blueprint: Blueprint, index: string): Sql$1;
398
470
  protected type(column: ColumnDefinition): Sql$1;
@@ -400,17 +472,34 @@ declare class SqliteSchemaGrammar extends SchemaGrammar {
400
472
  compileTables(): Sql$1;
401
473
  compileColumns(table: string): Sql$1;
402
474
  normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[];
475
+ /** Laravel's query: the primary key from pragma_table_xinfo, then every index of pragma_index_list with its columns. */
476
+ compileIndexes(table: string): Sql$1;
477
+ /** A table whose primary key has its own index (not a rowid alias) lists it twice: the index entry is kept. */
478
+ normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[];
479
+ compileForeignKeys(table: string): Sql$1;
480
+ normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[];
403
481
  compileEnableForeignKeyConstraints(): Sql$1;
404
482
  compileDisableForeignKeyConstraints(): Sql$1;
405
483
  }
406
484
  declare class PostgresSchemaGrammar extends SchemaGrammar {
407
485
  readonly driver: "pgsql";
486
+ /** A changed column's comment is set again, or cleared (`is NULL`) when the new definition has none (Laravel 11+). */
408
487
  protected compileComments(blueprint: Blueprint): Sql$1[];
488
+ /**
489
+ * Laravel's compileChange(): `alter column` for the type, the nullability and the default, in one statement. A serial
490
+ * type becomes its integer type (the sequence stays), and an auto-increment column keeps its default. No `using`
491
+ * clause: a change Postgres can't cast implicitly fails, as in Laravel.
492
+ */
493
+ protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[];
409
494
  protected type(column: ColumnDefinition): Sql$1;
410
495
  protected modifiers(column: ColumnDefinition): Sql$1[];
411
496
  compileTables(): Sql$1;
412
497
  compileColumns(table: string): Sql$1;
413
498
  normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[];
499
+ compileIndexes(table: string): Sql$1;
500
+ normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[];
501
+ compileForeignKeys(table: string): Sql$1;
502
+ normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[];
414
503
  compileEnableForeignKeyConstraints(): Sql$1;
415
504
  compileDisableForeignKeyConstraints(): Sql$1;
416
505
  }
@@ -418,6 +507,8 @@ declare class MySqlSchemaGrammar extends SchemaGrammar {
418
507
  readonly driver: "mysql";
419
508
  protected compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql$1;
420
509
  protected compileAdd(blueprint: Blueprint): Sql$1[];
510
+ /** Laravel's compileChange(): `modify` with the column's whole new definition. */
511
+ protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[];
421
512
  protected compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql$1;
422
513
  protected compileIndex(blueprint: Blueprint, index: string, columns: string[]): Sql$1;
423
514
  protected compileDropPrimary(blueprint: Blueprint): Sql$1;
@@ -429,6 +520,10 @@ declare class MySqlSchemaGrammar extends SchemaGrammar {
429
520
  compileTables(): Sql$1;
430
521
  compileColumns(table: string): Sql$1;
431
522
  normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[];
523
+ compileIndexes(table: string): Sql$1;
524
+ normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[];
525
+ compileForeignKeys(table: string): Sql$1;
526
+ normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[];
432
527
  compileEnableForeignKeyConstraints(): Sql$1;
433
528
  compileDisableForeignKeyConstraints(): Sql$1;
434
529
  }
@@ -451,7 +546,10 @@ declare class SchemaBuilder {
451
546
  drop(table: string): Promise<void>;
452
547
  dropIfExists(table: string): Promise<void>;
453
548
  rename(from: string, to: string): Promise<void>;
454
- /** Runs a blueprint's statements. Also useful to inspect the DDL: grammar.compile(blueprint). */
549
+ /**
550
+ * Runs a blueprint's statements in order (inspect them with grammar.compile(blueprint)). On SQLite, a change to the
551
+ * keys of an existing table rebuilds it from its live definition at its place in that order.
552
+ */
455
553
  build(blueprint: Blueprint): Promise<void>;
456
554
  /** The table names of the connection's database (or current schema on Postgres). */
457
555
  getTables(): Promise<string[]>;
@@ -461,6 +559,16 @@ declare class SchemaBuilder {
461
559
  /** Case-insensitive, like Laravel. */
462
560
  hasColumn(table: string, column: string): Promise<boolean>;
463
561
  hasColumns(table: string, columns: string[]): Promise<boolean>;
562
+ /** The table's indexes, its primary key included (Laravel's getIndexes()). */
563
+ getIndexes(table: string): Promise<IndexInfo[]>;
564
+ getIndexListing(table: string): Promise<string[]>;
565
+ /**
566
+ * Whether the table has an index with this name, or on exactly these columns (in order). `type` narrows it:
567
+ * 'primary', 'unique', or an index method such as 'btree'.
568
+ */
569
+ hasIndex(table: string, index: string | string[], type?: string): Promise<boolean>;
570
+ /** The table's foreign keys (Laravel's getForeignKeys()). */
571
+ getForeignKeys(table: string): Promise<ForeignKeyInfo[]>;
464
572
  enableForeignKeyConstraints(): Promise<void>;
465
573
  disableForeignKeyConstraints(): Promise<void>;
466
574
  /**
@@ -732,6 +840,13 @@ declare class Grammar {
732
840
  compileOrders(query: Builder$1<unknown>): Sql | undefined;
733
841
  compileWheres(wheres: readonly Where[], keyword?: 'where' | 'on'): Sql | undefined;
734
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;
735
850
  /**
736
851
  * whereLike() per driver, as Laravel 12's grammars: Postgres compares the column as text with ilike (like when
737
852
  * case-sensitive); MySQL uses like (like binary); SQLite uses like, or glob with the pattern translated.
@@ -814,7 +929,20 @@ type Where = {
814
929
  sql: string;
815
930
  bindings: readonly unknown[];
816
931
  boolean: WhereBoolean;
932
+ } | {
933
+ type: 'date';
934
+ part: DatePart;
935
+ column: ColumnRef;
936
+ operator: string;
937
+ value: unknown;
938
+ boolean: WhereBoolean;
817
939
  };
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];
818
946
  type Having = {
819
947
  column: ColumnRef;
820
948
  operator: string;
@@ -830,9 +958,11 @@ type Order = {
830
958
  } | {
831
959
  raw: Expression;
832
960
  };
961
+ /** A column, an expression, or `(subquery) as alias` (`exists (subquery) as alias` with exists). */
833
962
  type SelectColumn = ColumnRef | {
834
963
  query: Builder$1<unknown>;
835
964
  as: string;
965
+ exists?: boolean;
836
966
  };
837
967
  type NestedCallback<Q> = (query: Q) => unknown;
838
968
  /** The value when()'s callback receives: the condition's type without its falsy members. */
@@ -887,6 +1017,21 @@ declare class Builder$1<T = Row> implements QueryBuilder<T> {
887
1017
  whereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
888
1018
  orWhereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
889
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;
890
1035
  /**
891
1036
  * Laravel's whereLike(): the value is the pattern, `%` and `_` included (`whereLike('title', `%${term}%`)`).
892
1037
  * Case-insensitive unless caseSensitive: ilike on Postgres, like on MySQL and SQLite (their like already ignores
@@ -947,6 +1092,8 @@ declare class Builder$1<T = Row> implements QueryBuilder<T> {
947
1092
  unless<V>(value: V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: Truthy<V>) => unknown): this;
948
1093
  tap(callback: (query: this) => unknown): this;
949
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>;
950
1097
  /** The raw rows, without a Collection around them. */
951
1098
  runSelect(): Promise<T[]>;
952
1099
  first(): Promise<T | undefined>;
@@ -1027,6 +1174,8 @@ declare class Builder$1<T = Row> implements QueryBuilder<T> {
1027
1174
  private subQuery;
1028
1175
  private addNested;
1029
1176
  private addWhere;
1177
+ /** Laravel's addDateBasedWhere(): one value means '='; the operator is checked against the whitelist. */
1178
+ private addDateBasedWhere;
1030
1179
  private pushNull;
1031
1180
  }
1032
1181
  type JoinType = 'inner' | 'left' | 'right' | 'cross';
@@ -1134,6 +1283,106 @@ declare const SchemaBuilderToken: Token<SchemaBuilder>;
1134
1283
  /** The Schema facade: Schema.create('posts', (t) => { … }), Schema.table(…), Schema.dropIfExists(…). */
1135
1284
  declare const Schema: _orieljs_support.Facade<SchemaBuilder, object>;
1136
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;
1293
+ }
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;
1311
+
1312
+ /**
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.
1317
+ */
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>;
1351
+ /**
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).
1354
+ */
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
+
1137
1386
  /**
1138
1387
  * A relation is the related model's query builder, constrained to the parent: post.comments() is a
1139
1388
  * Builder<Comment> with `where comments.post_id = ?`, so every builder method (where, orderBy, paginate, a local
@@ -1235,6 +1484,8 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1235
1484
  protected scopes: Map<string, GlobalScope>;
1236
1485
  protected removedScopes: string[];
1237
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>;
1238
1489
  constructor(model: M);
1239
1490
  getModel(): M;
1240
1491
  /** The model class's static scope<Name> method for a builder method name, if any. */
@@ -1265,6 +1516,16 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1265
1516
  whereNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this;
1266
1517
  whereNotNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this;
1267
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;
1268
1529
  whereLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean, boolean?: WhereBoolean, not?: boolean): this;
1269
1530
  orWhereLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean): this;
1270
1531
  whereNotLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean, boolean?: WhereBoolean): this;
@@ -1277,6 +1538,12 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1277
1538
  /** where key = id (or key in ids). */
1278
1539
  whereKey(id: unknown): this;
1279
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>;
1280
1547
  /** Runs the query, hydrates models, fires their retrieved events and eager loads the with() relations. */
1281
1548
  runSelect(): Promise<M[]>;
1282
1549
  /**
@@ -1299,6 +1566,25 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1299
1566
  * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.
1300
1567
  */
1301
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.
1584
+ */
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;
1302
1588
  /**
1303
1589
  * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').
1304
1590
  * Uses `exists (…)` for the common "at least one"/"none" cases and a count subquery otherwise.
@@ -1325,9 +1611,9 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1325
1611
  protected isMalformedKey(id: unknown): boolean;
1326
1612
  /** A malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. */
1327
1613
  find(id: unknown): Promise<M | undefined>;
1328
- findMany(ids: readonly unknown[]): Promise<Collection<M>>;
1614
+ findMany(ids: readonly unknown[]): Promise<EloquentCollection<M>>;
1329
1615
  /** find(), or ModelNotFoundError (a 404). With an array, every id must exist. */
1330
- findOrFail(ids: readonly unknown[]): Promise<Collection<M>>;
1616
+ findOrFail(ids: readonly unknown[]): Promise<EloquentCollection<M>>;
1331
1617
  findOrFail(id: unknown): Promise<M>;
1332
1618
  findOr<R>(id: unknown, callback: () => R | Promise<R>): Promise<M | R>;
1333
1619
  firstOrFail(): Promise<M>;
@@ -1373,32 +1659,6 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1373
1659
  protected defaultPerPage(): number;
1374
1660
  }
1375
1661
 
1376
- /**
1377
- * A custom cast (Laravel's CastsAttributes): get() turns the stored value into what the model exposes, set() turns
1378
- * an assigned value back into what is stored.
1379
- */
1380
- interface CastsAttributes<TGet = unknown, TSet = TGet> {
1381
- get(model: object, key: string, value: unknown, attributes: Row): TGet;
1382
- set(model: object, key: string, value: TSet, attributes: Row): unknown;
1383
- }
1384
- /** A TypeScript enum object (string or numeric) used as a cast: casts = { status: PostStatus }. */
1385
- type EnumLike = Record<string, string | number>;
1386
- type BuiltInCast = 'int' | 'integer' | 'float' | 'double' | 'real' | 'string' | 'bool' | 'boolean' | 'array' | 'json' | 'object' | 'collection' | 'date' | 'datetime' | 'immutable_date' | 'immutable_datetime' | 'timestamp' | `decimal:${number}`;
1387
- type CastDefinition = BuiltInCast | EnumLike | CastsAttributes | (new () => CastsAttributes);
1388
- /** The values of a TypeScript enum. Numeric enums also map values back to names; those reverse entries are skipped. */
1389
- declare function enumValues(cast: EnumLike): Array<string | number>;
1390
- declare const isJsonCast: (cast: CastDefinition | undefined) => boolean;
1391
- declare const isDateCast: (cast: CastDefinition | undefined) => boolean;
1392
- /** Laravel's castAttribute(): the stored value → the value the model exposes. null stays null (except custom casts). */
1393
- declare function castGet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
1394
- /** The value assigned to a cast attribute → the value stored in the model's attributes (and later bound). */
1395
- declare function castSet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
1396
- /**
1397
- * Laravel's originalIsEquivalent(): does the stored value still mean the same thing as the original?
1398
- * Keeps save() from writing columns whose value only changed representation (1 vs true, '5' vs 5, same instant).
1399
- */
1400
- declare function isEquivalent(cast: CastDefinition | undefined, current: unknown, original: unknown, model: object, key: string, className: string): boolean;
1401
-
1402
1662
  declare const MANY: unique symbol;
1403
1663
  /** Type-level marker set by count(): make()/create() then return a Collection. */
1404
1664
  interface Many {
@@ -1415,6 +1675,17 @@ interface StateContext {
1415
1675
  }
1416
1676
  type State = Row | ((attributes: Row, context: StateContext) => Row);
1417
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
+ }
1418
1689
  /**
1419
1690
  * A model's factory() typed as its own factory class (Laravel's `@use HasFactory<UserFactory>`): declare it in the
1420
1691
  * model, `declare static factory: HasFactory<UserFactory>` (with `import type`), and User.factory().unverified()
@@ -1425,12 +1696,12 @@ type HasFactory<F> = {
1425
1696
  (count: number, state?: State): F & Many;
1426
1697
  } & (typeof Model)['factory'];
1427
1698
  interface HasRelationship {
1428
- factory: AnyFactory;
1699
+ factory: RelatedFactory;
1429
1700
  relationship: string;
1430
1701
  pivot: Row;
1431
1702
  }
1432
1703
  interface ForRelationship {
1433
- parent: AnyFactory | Model;
1704
+ parent: RelatedFactory | Model;
1434
1705
  relationship: string;
1435
1706
  resolved?: Model;
1436
1707
  }
@@ -1476,9 +1747,9 @@ declare abstract class Factory<M extends Model = Model> {
1476
1747
  /** deleted_at = now, for soft-deleting models. */
1477
1748
  trashed(): this;
1478
1749
  /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */
1479
- has(factory: AnyFactory, relationship?: string, pivot?: Row): this;
1750
+ has(factory: RelatedFactory, relationship?: string, pivot?: Row): this;
1480
1751
  /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */
1481
- for(parent: AnyFactory | Model, relationship?: string): this;
1752
+ for(parent: RelatedFactory | Model, relationship?: string): this;
1482
1753
  afterMaking(callback: (model: M) => unknown): this;
1483
1754
  afterCreating(callback: (model: M) => unknown): this;
1484
1755
  /** The attributes only, without a model (a Row, or a Row[] after count()). */
@@ -1550,7 +1821,7 @@ interface SyncChanges {
1550
1821
  * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).
1551
1822
  * Each related model carries its pivot row as `tag.pivot` (withPivot() adds columns, withTimestamps() the timestamps).
1552
1823
  */
1553
- declare class BelongsToMany<R extends Model, P extends Model = Model> extends Relation<R, P, Collection<R>> {
1824
+ declare class BelongsToMany<R extends Model, P extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {
1554
1825
  readonly table: string;
1555
1826
  readonly foreignPivotKey: string;
1556
1827
  readonly relatedPivotKey: string;
@@ -1574,7 +1845,7 @@ declare class BelongsToMany<R extends Model, P extends Model = Model> extends Re
1574
1845
  wherePivotIn(column: string, values: readonly unknown[]): this;
1575
1846
  /** Selects the related columns plus the pivot columns (as pivot_*), then moves those onto each model's pivot. */
1576
1847
  runSelect(): Promise<R[]>;
1577
- getResults(): Promise<Collection<R>>;
1848
+ getResults(): Promise<EloquentCollection<R>>;
1578
1849
  initRelation(models: P[], relation: string): P[];
1579
1850
  match(models: P[], results: R[], relation: string): P[];
1580
1851
  getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
@@ -1675,8 +1946,8 @@ declare abstract class HasOneOrMany<R extends Model, P extends Model, Result> ex
1675
1946
  }
1676
1947
 
1677
1948
  /** post.comments(): many related rows hold the parent's key. */
1678
- declare class HasMany<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, Collection<R>> {
1679
- getResults(): Promise<Collection<R>>;
1949
+ declare class HasMany<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, EloquentCollection<R>> {
1950
+ getResults(): Promise<EloquentCollection<R>>;
1680
1951
  initRelation(models: P[], relation: string): P[];
1681
1952
  match(models: P[], results: R[], relation: string): P[];
1682
1953
  }
@@ -1685,7 +1956,7 @@ declare class HasMany<R extends Model, P extends Model = Model> extends HasOneOr
1685
1956
  * Related rows reached through an intermediate model: country.posts() → hasManyThrough(Post, User):
1686
1957
  * posts join users on users.id = posts.user_id where users.country_id = countries.id.
1687
1958
  */
1688
- declare class HasManyThrough<R extends Model, P extends Model = Model, T extends Model = Model> extends Relation<R, P, Collection<R>> {
1959
+ declare class HasManyThrough<R extends Model, P extends Model = Model, T extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {
1689
1960
  readonly throughParent: T;
1690
1961
  readonly firstKey: string;
1691
1962
  readonly secondKey: string;
@@ -1712,8 +1983,8 @@ declare class HasManyThrough<R extends Model, P extends Model = Model, T extends
1712
1983
  addEagerConstraints(models: P[]): void;
1713
1984
  /** Selects the related columns plus the through key, then moves the key off the attributes. */
1714
1985
  runSelect(): Promise<R[]>;
1715
- getResults(): Promise<Collection<R>>;
1716
- getEager(): Promise<Collection<R>>;
1986
+ getResults(): Promise<EloquentCollection<R>>;
1987
+ getEager(): Promise<EloquentCollection<R>>;
1717
1988
  initRelation(models: P[], relation: string): P[];
1718
1989
  match(models: P[], results: R[], relation: string): P[];
1719
1990
  getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
@@ -1824,6 +2095,8 @@ declare class Model implements ModelInstance {
1824
2095
  raw: unknown;
1825
2096
  value: unknown;
1826
2097
  }>;
2098
+ /** Attributes with the hashed cast that were assigned a value since the last save; save() hashes them. */
2099
+ protected pendingHashes: Set<string>;
1827
2100
  constructor();
1828
2101
  /** Runs booting()/booted() once per class, the first time the class is instantiated. */
1829
2102
  static bootIfNotBooted(): void;
@@ -1874,6 +2147,13 @@ declare class Model implements ModelInstance {
1874
2147
  * Observer classes are resolved from the container.
1875
2148
  */
1876
2149
  static observe(...observers: Array<object | (new () => object)>): void;
2150
+ /**
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.
2154
+ */
2155
+ static warnOnRelationPropertyAccess(enabled?: boolean): void;
2156
+ static warnsOnRelationPropertyAccess(): boolean;
1877
2157
  /** Runs fn with model events off, for this async context only. */
1878
2158
  static withoutEvents<R>(fn: () => R): R;
1879
2159
  /** A new query of this model, with its global scopes. */
@@ -1894,6 +2174,12 @@ declare class Model implements ModelInstance {
1894
2174
  /** Post.whereLike('title', `%${term}%`): case-insensitive unless caseSensitive (see the query builder's whereLike()). */
1895
2175
  static whereLike<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, value: string, caseSensitive?: boolean): ModelBuilder<C>;
1896
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>;
1897
2183
  static whereColumn<C extends typeof Model>(this: C, first: Column<Instance<C>>, operatorOrSecond: string, second?: Column<Instance<C>>): ModelBuilder<C>;
1898
2184
  static whereRaw<C extends typeof Model>(this: C, sql: string, bindings?: readonly unknown[]): ModelBuilder<C>;
1899
2185
  static select<C extends typeof Model>(this: C, ...columns: Array<Column<Instance<C>> | Expression>): ModelBuilder<C>;
@@ -1908,6 +2194,13 @@ declare class Model implements ModelInstance {
1908
2194
  /** Eager loads relations: Post.with('author', 'comments.user').get(). */
1909
2195
  static with<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C>;
1910
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>;
1911
2204
  static has<C extends typeof Model>(this: C, relation: string, operator?: string, count?: number): ModelBuilder<C>;
1912
2205
  static whereHas<C extends typeof Model>(this: C, relation: string, callback?: RelationConstraint, operator?: string, count?: number): ModelBuilder<C>;
1913
2206
  static doesntHave<C extends typeof Model>(this: C, relation: string): ModelBuilder<C>;
@@ -1917,11 +2210,11 @@ declare class Model implements ModelInstance {
1917
2210
  /** Soft deletes: only trashed rows. */
1918
2211
  static onlyTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
1919
2212
  static withoutTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
1920
- static all<C extends typeof Model>(this: C): Promise<Collection<Instance<C>>>;
2213
+ static all<C extends typeof Model>(this: C): Promise<EloquentCollection<Instance<C>>>;
1921
2214
  static find<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | undefined>;
1922
- static findOrFail<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<Collection<Instance<C>>>;
2215
+ static findOrFail<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>;
1923
2216
  static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C>>;
1924
- static findMany<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<Collection<Instance<C>>>;
2217
+ static findMany<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>;
1925
2218
  static first<C extends typeof Model>(this: C): Promise<Instance<C> | undefined>;
1926
2219
  static firstOrFail<C extends typeof Model>(this: C): Promise<Instance<C>>;
1927
2220
  static firstWhere<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, operatorOrValue: unknown, value?: unknown): Promise<Instance<C> | undefined>;
@@ -1931,8 +2224,8 @@ declare class Model implements ModelInstance {
1931
2224
  static paginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<LengthAwarePaginator<Instance<C>>>;
1932
2225
  static simplePaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<Paginator<Instance<C>>>;
1933
2226
  static cursorPaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], cursorName?: string, cursor?: Cursor | string): Promise<CursorPaginator<Instance<C>>>;
1934
- static chunk<C extends typeof Model>(this: C, count: number, callback: (models: Collection<Instance<C>>, page: number) => unknown): Promise<boolean>;
1935
- static chunkById<C extends typeof Model>(this: C, count: number, callback: (models: Collection<Instance<C>>, page: number) => unknown): Promise<boolean>;
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>;
1936
2229
  static each<C extends typeof Model>(this: C, callback: (model: Instance<C>, index: number) => unknown, count?: number): Promise<boolean>;
1937
2230
  static lazy<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>>;
1938
2231
  static lazyById<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>>;
@@ -1976,6 +2269,8 @@ declare class Model implements ModelInstance {
1976
2269
  hasSetMutator(key: string): boolean;
1977
2270
  /** Every cast, including the implied ones: the incrementing key (int) and the timestamp columns (datetime). */
1978
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;
1979
2274
  hasCast(key: string, types?: string[]): boolean;
1980
2275
  /** The stored attributes, with in-place changes to json casts written back. */
1981
2276
  getAttributes(): Row;
@@ -2073,6 +2368,14 @@ declare class Model implements ModelInstance {
2073
2368
  * runs no query at all. Returns false when a saving/creating/updating listener cancels.
2074
2369
  */
2075
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.
2377
+ */
2378
+ protected hashPendingAttributes(): Promise<void>;
2076
2379
  /** Fills and saves an existing model. */
2077
2380
  update(attributes?: Row): Promise<boolean>;
2078
2381
  /**
@@ -2173,7 +2476,7 @@ declare class Model implements ModelInstance {
2173
2476
  getRelationInstance(name: string): Relation;
2174
2477
  /**
2175
2478
  * A loaded relation, typed from the relation method: post.getRelation('author') is User | null,
2176
- * post.getRelation('comments') is Collection<Comment>. Throws RelationNotLoadedError when it isn't loaded
2479
+ * post.getRelation('comments') is EloquentCollection<Comment>. Throws RelationNotLoadedError when it isn't loaded
2177
2480
  * (JavaScript can't lazy-load synchronously: use with(), load() or post.comments().get()).
2178
2481
  */
2179
2482
  getRelation<K extends RelationNames<this>>(name: K): RelationValue<this, K>;
@@ -2183,6 +2486,20 @@ declare class Model implements ModelInstance {
2183
2486
  loadMissing(...relations: string[]): Promise<this>;
2184
2487
  /** Loads <relation>_count attributes: await post.loadCount('comments'). */
2185
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>;
2498
+ /**
2499
+ * The collection queries of this model return (Laravel's newCollection()): an EloquentCollection. Override it to
2500
+ * return a subclass with your own methods.
2501
+ */
2502
+ newCollection<T extends Model>(this: T, models?: T[]): EloquentCollection<T>;
2186
2503
  /** Stores a loaded relation (eager loading and load() use this). */
2187
2504
  setRelation(name: string, value: unknown): this;
2188
2505
  relationLoaded(name: string): boolean;
@@ -2260,13 +2577,15 @@ declare class DatabaseNotification extends DatabaseNotification_base implements
2260
2577
  markAsUnread(): Promise<void>;
2261
2578
  read(): boolean;
2262
2579
  unread(): boolean;
2580
+ /** Queries of notifications return a DatabaseNotificationCollection (markAsRead() on all of them). */
2581
+ newCollection<T extends Model>(this: T, models?: T[]): EloquentCollection<T>;
2263
2582
  /** `query.read()`: only read notifications. */
2264
2583
  static scopeRead(query: Builder<DatabaseNotification>): Builder<DatabaseNotification>;
2265
2584
  /** `query.unread()`: only unread notifications. */
2266
2585
  static scopeUnread(query: Builder<DatabaseNotification>): Builder<DatabaseNotification>;
2267
2586
  }
2268
2587
  /** Laravel's DatabaseNotificationCollection: what `await user.notifications().get()` returns. */
2269
- declare class DatabaseNotificationCollection extends Collection<DatabaseNotification> {
2588
+ declare class DatabaseNotificationCollection extends EloquentCollection<DatabaseNotification> {
2270
2589
  /** Marks every notification as read (one save each, as in Laravel). */
2271
2590
  markAsRead(): Promise<void>;
2272
2591
  /** Marks every notification as unread. */
@@ -2448,6 +2767,14 @@ declare class Migrator {
2448
2767
  private rollDown;
2449
2768
  /** Runs up/down on the migration's connection (made the default meanwhile), in a transaction where DDL allows it. */
2450
2769
  private runMigration;
2770
+ /**
2771
+ * SQLite's order for a migration in a transaction: foreign keys off before the transaction (SQLite ignores the pragma
2772
+ * inside one, and a table rebuild would otherwise run the ON DELETE actions of the tables that reference it), the
2773
+ * migration, a foreign key check before the commit (rows that break a key fail the migration), then foreign keys back
2774
+ * on. A migration outside a transaction runs with foreign keys as they are, so its ON DELETE and ON UPDATE actions
2775
+ * run; a table rebuild in it turns them off around itself and checks the table.
2776
+ */
2777
+ private runOnSqlite;
2451
2778
  }
2452
2779
 
2453
2780
  type SeederClass = new () => Seeder;
@@ -2641,4 +2968,4 @@ declare class DatabaseServiceProvider extends ServiceProvider {
2641
2968
  private manager;
2642
2969
  }
2643
2970
 
2644
- 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 Direction, type EagerLoadSpec, type EnumLike, Expression, Factory, type FactoryResult, Faker, FakerOverflowError, ForeignIdColumnDefinition, ForeignKeyDefinition, type GlobalScope, Grammar, HasDatabaseNotifications, type HasDatabaseNotificationsModel, type HasFactory, HasMany, HasManyThrough, HasOne, HasOneOrMany, HasUlids, HasUuids, type Having, 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 Scope, type ScopeCallback, type ScopeStatic, type Scopes, Seeder, type SeederClass, type SelectColumn, SoftDeletingScope, SqliteSchemaGrammar, type State, type StateContext, type SyncChanges, 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, loadRelations, migrationDatePrefix, modelEventName, morphMap, mysqlPoolOptions, openSqlite, parseDateTime, prepareValue, raw, rawWithBindings, registerMigrationCommands, registerModelTypesCommand, resolveMorphClass, runSeeder, serializeDate, usePaginationResolvers };
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 };