-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
model.ts
1242 lines (1084 loc) · 30.6 KB
/
model.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* @adonisjs/lucid
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { DateTime } from 'luxon'
import type Hooks from '@poppinss/hooks'
import { DialectContract, QueryClientContract, TransactionClientContract } from './database.js'
import {
Update,
Counter,
OneOrMany,
Aggregate,
Returning,
ChainableContract,
SimplePaginatorMetaKeys,
SimplePaginatorContract,
ExcutableQueryBuilderContract,
} from './querybuilder.js'
import {
ExtractModelRelations,
Has,
ManyToManyRelationOptions,
ModelRelationTypes,
ModelRelations,
Preload,
PreloaderContract,
RelationOptions,
RelationshipsContract,
ThroughRelationOptions,
WhereHas,
WithAggregate,
WithCount,
} from './relations.js'
/**
* ------------------------------------------------------
* Helpers
* ------------------------------------------------------
*/
/**
* Same as [[Parameters]] but omits the first parameter
*/
type OmitFirst<T extends (...args: any) => any> = T extends (x: any, ...args: infer P) => any
? P
: never
/**
* Same as [[Pick]] but picks by value and not the key
*/
type PickProperties<T, P> = Pick<T, { [K in keyof T]: T[K] extends P ? K : never }[keyof T]>
/**
* Decorator function
*/
export type DecoratorFn = (target: any, property: any) => void
/**
* Typed decorator
*/
export type TypedDecorator<PropType> = <
TKey extends string,
TTarget extends { [K in TKey]: PropType },
>(
target: TTarget,
property: TKey
) => void
/**
* Typed decorator that also represents an optional property
*/
export type OptionalTypedDecorator<PropType> = <
TKey extends string,
TTarget extends { [K in TKey]?: PropType },
>(
target: TTarget,
property: TKey
) => void
/**
* A complex type that filters out functions and relationships from the
* model attributes and consider all other properties as database
* columns. Alternatively, the user can self define a `$columns`
* property.
*/
export type ModelAttributes<Model extends LucidRow> = Model['$columns'] extends undefined
? {
[Filtered in {
[P in keyof Model]: P extends keyof LucidRow | 'serializeExtras'
? never
: Model[P] extends Function | ModelRelationTypes
? never
: P
}[keyof Model]]: Model[Filtered]
}
: Model['$columns']
/**
* Extract the query scopes of a model
*/
export type ExtractScopes<Model extends LucidModel> = {
[Scope in keyof PickProperties<Model, QueryScope<Model, QueryScopeCallback<Model>>>]: (
...args: Model[Scope] extends QueryScopeCallback<Model> ? OmitFirst<Model[Scope]> : never
) => ExtractScopes<Model>
}
/**
* Reusable interface to define an object.
*/
export interface ModelObject {
[key: string]: any
}
/**
* Shape of cache node to keep getters optimized
*/
export type CacheNode = {
original: any
resolved: any
getter: (value: any) => any
}
/**
* Shape for cherry picking fields
*/
export type CherryPickFields =
| string[]
| {
pick?: string[]
omit?: string[]
}
/**
* Shape for cherry picking fields on nested relationships
*/
export type CherryPick = {
fields?: CherryPickFields
relations?: { [relation: string]: CherryPick }
}
/**
* List of events for which a model will trigger hooks
*/
export type EventsList = 'save' | 'create' | 'update' | 'delete' | 'fetch' | 'find' | 'paginate'
export type HooksHandler<Data, Event extends EventsList> = (
data: Data,
event: Event
) => Promise<void> | void
/**
* ------------------------------------------------------
* Query Scope
* ------------------------------------------------------
*/
/**
* Generic query scope callback
*/
export type QueryScopeCallback<Model extends LucidModel = LucidModel> = (
query: ModelQueryBuilderContract<Model>,
...args: any[]
) => void
/**
* Query scope
*/
export type QueryScope<
Model extends LucidModel,
Scope extends QueryScopeCallback<Model>,
> = Scope & {
readonly isQueryScope: true
}
/**
* A function to mark a method as query scope
*/
export type ScopeFn = <
Model extends LucidModel,
Scope extends QueryScopeCallback<Model> = QueryScopeCallback<Model>,
>(
callback: Scope
) => QueryScope<Model, Scope>
/**
* ------------------------------------------------------
* Decorators and Options
* ------------------------------------------------------
*/
/**
* Options for defining a column
*/
export type ColumnOptions = {
columnName: string // database column name
serializeAs: string | null // null means do not serialize column
isPrimary: boolean
meta?: any
/**
* Invoked before serializing process happens
*/
serialize?: (value: any, attribute: string, model: LucidRow) => any
/**
* Invoked before create or update happens
*/
prepare?: (value: any, attribute: string, model: LucidRow) => any
/**
* Invoked when row is fetched from the database
*/
consume?: (value: any, attribute: string, model: LucidRow) => any
}
/**
* Shape of column options after they have set on the model
*/
export type ModelColumnOptions = ColumnOptions & {
hasGetter: boolean
hasSetter: boolean
}
/**
* Represents a computed property on the model
*/
export type ComputedOptions = {
serializeAs: string | null
meta?: any
}
/**
* Options accepted by the Model.$addRelation method
*/
export type ModelRelationOptions =
| RelationOptions<LucidModel, LucidModel, ModelRelations<LucidModel, LucidModel>>
| ManyToManyRelationOptions<ModelRelations<LucidModel, LucidModel>>
| ThroughRelationOptions<LucidModel, LucidModel, ModelRelations<LucidModel, LucidModel>>
/**
* Signature for column decorator function
*/
export type ColumnDecorator = (options?: Partial<ColumnOptions>) => DecoratorFn
/**
* Signature for computed decorator function
*/
export type ComputedDecorator = (options?: Partial<ComputedOptions>) => DecoratorFn
/**
* Decorator for defining date columns
*/
export type DateColumnDecorator = (
options?: Partial<
ColumnOptions & {
autoCreate: boolean
autoUpdate: boolean
}
>
) => OptionalTypedDecorator<DateTime | null>
/**
* Decorator for defining date time columns. It is same as
* date column as of now
*/
export type DateTimeColumnDecorator = DateColumnDecorator
/**
* Decorator for defining hooks. The generics enforces that
* decorator is used on static properties only
*/
export type HooksDecorator = () => <Model extends LucidModel>(
target: Model,
property: string
) => void
/**
* ------------------------------------------------------
* Model Options
* ------------------------------------------------------
*/
/**
* Model options to be used when making queries
*/
export type ModelOptions = {
connection?: string
}
/**
* Adapter also accepts a client directly
*/
export type ModelAdapterOptions = ModelOptions & {
client?: QueryClientContract
}
/**
* Options used by the method that internally invokes
* the merge method.
] */
export type ModelAssignOptions = ModelAdapterOptions & {
allowExtraProperties?: boolean
}
/**
* Preload function on a model instance
*/
export interface LucidRowPreload<Model extends LucidRow> extends Preload<Model, Promise<void>> {
(callback: (preloader: PreloaderContract<Model>) => void): Promise<void>
}
export interface LucidRowAggregate<Model extends LucidRow> extends Preload<Model, Promise<void>> {
(callback: (preloader: PreloaderContract<Model>) => void): Promise<void>
}
/**
* An extension of the simple paginator with support for serializing models
*/
export interface ModelPaginatorContract<Result extends LucidRow>
extends Omit<SimplePaginatorContract<Result>, 'toJSON'> {
serialize(cherryPick?: CherryPick): { meta: any; data: ModelObject[] }
toJSON(): { meta: any; data: ModelObject[] }
}
/**
* Lazy load aggregates for a given model instance
*/
export interface LazyLoadAggregatesContract<Model extends LucidRow> extends Promise<void> {
loadAggregate: WithAggregate<Model, this>
loadCount: WithCount<Model, this>
exec(): Promise<void>
}
/**
* ------------------------------------------------------
* Model Query Builder
* ------------------------------------------------------
*/
/**
* Model query builder will have extras methods on top of the Database query builder
*/
export interface ModelQueryBuilderContract<Model extends LucidModel, Result = InstanceType<Model>>
extends ChainableContract,
ExcutableQueryBuilderContract<Result[]> {
model: Model
returning: Returning<this>
/**
* Define a callback to transform a row
*/
rowTransformer(callback: (row: LucidRow) => void): this
/**
* Define a custom preloader for the current query
*/
usePreloader(preloader: PreloaderContract<LucidRow>): this
/**
* Whether or not the query is a child query generated for `.where`
* callbacks
*/
isChildQuery: boolean
/**
* Alias for the @withScopes method
*/
apply<Scopes extends ExtractScopes<Model>>(callback: (scopes: Scopes) => void): this
/**
* Apply model query scopes on the query bulder
*/
withScopes<Scopes extends ExtractScopes<Model>>(callback: (scopes: Scopes) => void): this
/**
* A copy of client options.
*/
readonly clientOptions: ModelAdapterOptions
/**
* Reference to query client used for making queries
*/
client: QueryClientContract
/**
* Clone query builder instance
*/
clone<ClonedResult = Result>(): ModelQueryBuilderContract<Model, ClonedResult>
/**
* A custom set of sideloaded properties defined on the query
* builder, this will be passed to the model instance created
* by the query builder
*/
sideload(value: ModelObject): this
/**
* Execute and get first result
*/
first(): Promise<Result | null>
/**
* Return the first matching row or fail
*/
firstOrFail(): Promise<Result>
/**
* Perform delete operation
*/
del(returning?: OneOrMany<string>): ModelQueryBuilderContract<Model, any>
delete(returning?: OneOrMany<string>): ModelQueryBuilderContract<Model, any>
/**
* A shorthand to define limit and offset based upon the
* current page
*/
forPage(page: number, perPage?: number): this
/**
* Execute query with pagination
*/
paginate(
page: number,
perPage?: number
): Promise<
Result extends LucidRow ? ModelPaginatorContract<Result> : SimplePaginatorContract<Result>
>
/**
* Mutations (update and increment can be one query aswell)
*/
update: Update<ModelQueryBuilderContract<Model, any>>
increment: Counter<ModelQueryBuilderContract<Model, any>>
decrement: Counter<ModelQueryBuilderContract<Model, any>>
/**
* Fetch relationship count
*/
withCount: WithCount<InstanceType<Model>, this>
/**
* Fetch aggregate value for a given relationship
*/
withAggregate: WithAggregate<InstanceType<Model>, this>
/**
* Add where constraint using the relationship
*/
has: Has<InstanceType<Model>, this>
orHas: Has<InstanceType<Model>, this>
andHas: Has<InstanceType<Model>, this>
doesntHave: Has<InstanceType<Model>, this>
orDoesntHave: Has<InstanceType<Model>, this>
andDoesntHave: Has<InstanceType<Model>, this>
/**
* Add where constraint using the relationship with a custom callback
*/
whereHas: WhereHas<InstanceType<Model>, this>
orWhereHas: WhereHas<InstanceType<Model>, this>
andWhereHas: WhereHas<InstanceType<Model>, this>
whereDoesntHave: WhereHas<InstanceType<Model>, this>
orWhereDoesntHave: WhereHas<InstanceType<Model>, this>
andWhereDoesntHave: WhereHas<InstanceType<Model>, this>
/**
* Define relationships to be preloaded
*/
preload: Preload<InstanceType<Model>, this>
/**
* Aggregates
*/
count: Aggregate<this>
countDistinct: Aggregate<this>
min: Aggregate<this>
max: Aggregate<this>
sum: Aggregate<this>
sumDistinct: Aggregate<this>
avg: Aggregate<this>
avgDistinct: Aggregate<this>
/**
* Executes the callback when dialect matches one of the mentioned
* dialects
*/
ifDialect(
dialect: DialectContract['name'] | DialectContract['name'][],
matchCallback: (query: this) => any,
noMatchCallback?: (query: this) => any
): this
/**
* Executes the callback when dialect matches doesn't all the mentioned
* dialects
*/
unlessDialect(
dialect: DialectContract['name'] | DialectContract['name'][],
matchCallback: (query: this) => any,
noMatchCallback?: (query: this) => any
): this
/**
* Get rows back as a plain javascript object and not an array
* of model instances
*/
pojo<T>(): ModelQueryBuilderContract<Model, T>
}
/**
* Shape of model keys
*/
export interface ModelKeysContract {
add(key: string, value: string): void
get(key: string, defaultValue: string): string
get(key: string, defaultValue?: string): string | undefined
resolve(key: string): string
all(): ModelObject
}
/**
* ------------------------------------------------------
* Shape of Model instance
* ------------------------------------------------------
*/
/**
* Shape of the model instance. We prefix the properties with a `$` to
* differentiate between special properties provided by the base
* model but with exception to `save`, `delete`, `fill`, `merge`
* and `toJSON`.
*
* @note: Since the interface name appears next to the inherited model
* methods, we have to choose a succinct name
*/
export interface LucidRow {
$attributes: ModelObject
$extras: ModelObject
$original: ModelObject
$preloaded: { [relation: string]: LucidRow | LucidRow[] }
/**
* Columns is a property to get type information for model
* attributes. This must be declared by the end user
*/
$columns: undefined
$sideloaded: ModelObject
$primaryKeyValue?: number | string
$isPersisted: boolean
$isNew: boolean
$isLocal: boolean
$dirty: ModelObject
$isDirty: boolean
$isDeleted: boolean
$options?: ModelOptions
$trx?: TransactionClientContract
$setOptionsAndTrx(options?: ModelAdapterOptions): void
useTransaction(trx: TransactionClientContract): this
useConnection(connection: string): this
/**
* Gives an option to the end user to define constraints for update, insert
* and delete queries. Since the query builder for these queries aren't
* exposed to the end user, this method opens up the API to build
* custom queries.
*/
$getQueryFor(
action: 'insert',
client: QueryClientContract
): ReturnType<QueryClientContract['insertQuery']>
$getQueryFor(
action: 'update' | 'delete' | 'refresh',
client: QueryClientContract
): ModelQueryBuilderContract<LucidModel>
/**
* Read/write attributes. Following methods are intentionally loosely typed,
* so that one can bypass the public facing API and type checking for
* advanced use cases
*/
$setAttribute(key: string, value: any): void
$getAttribute(key: string): any
$getAttributeFromCache(key: string, callback: CacheNode['getter']): any
/**
* Read/write realtionships. Following methods are intentionally loosely typed,
* so that one can bypass the public facing API and type checking for
* advanced use cases
*/
$hasRelated(key: string): boolean
$setRelated(key: string, result: OneOrMany<LucidRow> | null): void
$pushRelated(key: string, result: OneOrMany<LucidRow> | null): void
$getRelated(key: string, defaultValue?: any): OneOrMany<LucidRow> | undefined | null
/**
* Consume the adapter result and hydrate the model
*/
$consumeAdapterResult(adapterResult: ModelObject, sideloadAttributes?: ModelObject): void
$hydrateOriginals(): void
fill(value: Partial<ModelAttributes<this>>, allowExtraProperties?: boolean): this
merge(value: Partial<ModelAttributes<this>>, allowExtraProperties?: boolean): this
/**
* Enable force update even when no attributes
* are dirty
*/
enableForceUpdate(): this
/**
* Actions to perform on the instance
*/
save(): Promise<this>
/**
* The lockForUpdate method re-fetches the model instance from
* the database and locks the row to perform an update. The
* provided callback receives a fresh user instance and should
* use that to perform an update.
*/
lockForUpdate<T>(callback: (user: this) => Promise<T> | T): Promise<T>
/**
* Perform delete by issuing a delete request on the adapter
*/
delete(): Promise<void>
/**
* Reload/Refresh the model instance
*/
refresh(): Promise<this>
/**
* Load relationships onto the instance
*/
load: LucidRowPreload<this>
/**
* Alias for "load"
* @deprecated
*/
preload: LucidRowPreload<this>
/**
* Load aggregates
*/
loadAggregate: <
Self extends this,
Name extends ExtractModelRelations<Self>,
RelatedBuilder = Self[Name] extends ModelRelations<LucidModel, LucidModel>
? Self[Name]['subQuery']
: never,
>(
name: Name,
callback: (builder: RelatedBuilder) => void
) => LazyLoadAggregatesContract<Self>
/**
* Load count
*/
loadCount: <
Self extends this,
Name extends ExtractModelRelations<Self>,
RelatedBuilder = Self[Name] extends ModelRelations<LucidModel, LucidModel>
? Self[Name]['subQuery']
: never,
>(
name: Name,
callback?: (builder: RelatedBuilder) => void
) => LazyLoadAggregatesContract<Self>
/**
* Serialize attributes to a plain object
*/
serializeAttributes(fields?: CherryPickFields, raw?: boolean): ModelObject
/**
* Serialize computed properties to a plain object
*/
serializeComputed(fields?: CherryPickFields): ModelObject
/**
* Serialize relationships to key-value pair of model instances and
* their serializeAs keys
*/
serializeRelations(fields: undefined, raw: true): { [key: string]: LucidRow | LucidRow[] }
/**
* Serialize relationships to key-value pair of plain nested objects
*/
serializeRelations(
cherryPick: CherryPick['relations'] | undefined,
raw: false | undefined
): ModelObject
serializeRelations(cherryPick?: CherryPick['relations'], raw?: boolean): ModelObject
/**
* Serialize model to a plain object
*/
serialize(cherryPick?: CherryPick): ModelObject
/**
* Converts model to an object. It just returns the properties
* of the model, along with preloaded relationships
*/
toObject(): ModelObject
/**
* Serialize everything
*/
toJSON(): ModelObject
/**
* Returns related model for a given relationship
*/
related<Name extends ExtractModelRelations<this>>(
relation: Name
): this[Name] extends ModelRelations<LucidModel, LucidModel> ? this[Name]['client'] : never
}
/**
* ------------------------------------------------------
* Shape of Model constructor
* ------------------------------------------------------
*/
/**
* Shape of the model static properties. The `$` prefix is to denote
* special properties from the base model.
*
* @note: Since the interface name appears next to the inherited model
* methods, we have to choose a succinct name
*/
export interface LucidModel {
/**
* Whether or not model has been booted. After this model configurations
* are ignored
*/
readonly booted: boolean
/**
* A map of defined columns
*/
$columnsDefinitions: Map<string, ModelColumnOptions>
/**
* A map of defined relationships
*/
$relationsDefinitions: Map<string, RelationshipsContract>
/**
* A map of computed properties
*/
$computedDefinitions: Map<string, ComputedOptions>
/**
* The primary key for finding unique referencing to a
* model
*/
primaryKey: string
/**
* Custom database connection to use
*/
connection?: string
/**
* Naming strategy to use
*/
namingStrategy: NamingStrategyContract
/**
* Database table to use
*/
table: string
/**
* Self assign the primary instead of relying on the database to
* return it back
*/
selfAssignPrimaryKey: boolean
/**
* Adapter to work as a bridge between query builder and the model
*/
$adapter: AdapterContract
/**
* Define an adapter to use for interacting with
* the database
*/
useAdapter(adapter: AdapterContract): void
/**
* Reference to hooks
*/
$hooks: Hooks<any>
/**
* A copy of internal keys mapping. One should be able to resolve between
* all key versions
*/
$keys: {
attributesToColumns: ModelKeysContract
attributesToSerialized: ModelKeysContract
columnsToAttributes: ModelKeysContract
columnsToSerialized: ModelKeysContract
serializedToColumns: ModelKeysContract
serializedToAttributes: ModelKeysContract
}
/**
* Creating model from adapter results
*/
$createFromAdapterResult<T extends LucidModel>(
this: T,
result?: ModelObject,
sideloadAttributes?: ModelObject,
options?: ModelAdapterOptions
): null | InstanceType<T>
/**
* Creating multiple model instances from an array of adapter
* result
*/
$createMultipleFromAdapterResult<T extends LucidModel>(
this: T,
results: ModelObject[],
sideloadAttributes?: ModelObject,
options?: ModelAdapterOptions
): InstanceType<T>[]
/**
* Managing columns
*/
$addColumn(name: string, options: Partial<ColumnOptions>): ColumnOptions
$hasColumn(name: string): boolean
$getColumn(name: string): ModelColumnOptions | undefined
/**
* Managing computed columns
*/
$addComputed(name: string, options: Partial<ComputedOptions>): ComputedOptions
$hasComputed(name: string): boolean
$getComputed(name: string): ComputedOptions | undefined
/**
* Managing relationships
*/
$addRelation(
name: string,
type: ModelRelationTypes['__opaque_type'],
relatedModel: () => LucidModel,
options: ModelRelationOptions
): void
/**
* Find if a relationship exists
*/
$hasRelation(name: string): boolean
/**
* Get relationship declaration
*/
$getRelation<Model extends LucidModel, Name extends ExtractModelRelations<InstanceType<Model>>>(
this: Model,
name: Name
): InstanceType<Model>[Name] extends ModelRelations<LucidModel, LucidModel>
? InstanceType<Model>[Name]['client']['relation']
: RelationshipsContract
$getRelation<Model extends LucidModel>(this: Model, name: string): RelationshipsContract
/**
* Define a static property on the model using the inherit or
* define strategy.
*
* Inherit strategy will clone the property from the parent model
* and will set it on the current model
*/
$defineProperty<Model extends LucidModel, Prop extends keyof Model>(
this: Model,
propertyName: Prop,
defaultValue: Model[Prop],
strategy: 'inherit' | 'define' | ((value: Model[Prop]) => Model[Prop])
): void
/**
* Boot model
*/
boot(): void
/**
* Register a before hook
*/
before<Model extends LucidModel, Event extends 'find' | 'fetch'>(
this: Model,
event: Event,
handler: HooksHandler<ModelQueryBuilderContract<Model>, Event>
): void
before<Model extends LucidModel>(
this: Model,
event: 'paginate',
handler: HooksHandler<
[ModelQueryBuilderContract<Model>, ModelQueryBuilderContract<Model>],
'paginate'
>
): void
before<Model extends LucidModel, Event extends EventsList>(
this: Model,
event: Event,
handler: HooksHandler<InstanceType<Model>, Event>
): void
/**
* Register an after hook
*/
after<Model extends LucidModel>(
this: Model,
event: 'fetch',
handler: HooksHandler<InstanceType<Model>[], 'fetch'>
): void
after<Model extends LucidModel>(
this: Model,
event: 'paginate',
handler: HooksHandler<ModelPaginatorContract<InstanceType<Model>>, 'paginate'>
): void
after<Model extends LucidModel, Event extends EventsList>(
this: Model,
event: Event,
handler: HooksHandler<InstanceType<Model>, Event>
): void
/**
* Create model and return its instance back
*/
create<T extends LucidModel>(
this: T,
values: Partial<ModelAttributes<InstanceType<T>>>,
options?: ModelAssignOptions
): Promise<InstanceType<T>>
/**
* Create many of model instances
*/
createMany<T extends LucidModel>(
this: T,
values: Partial<ModelAttributes<InstanceType<T>>>[],
options?: ModelAssignOptions
): Promise<InstanceType<T>[]>
/**
* Find one using the primary key
*/
find<T extends LucidModel>(
this: T,
value: any,
options?: ModelAdapterOptions
): Promise<null | InstanceType<T>>
/**
* Find one using the primary key or fail
*/
findOrFail<T extends LucidModel>(
this: T,
value: any,
options?: ModelAdapterOptions
): Promise<InstanceType<T>>
/**
* Find one using a key-value pair
*/
findBy<T extends LucidModel>(
this: T,
key: string,
value: any,
options?: ModelAdapterOptions
): Promise<null | InstanceType<T>>
/**
* Find one using a key-value pair or fail
*/
findByOrFail<T extends LucidModel>(
this: T,
key: string,
value: any,
options?: ModelAdapterOptions
): Promise<InstanceType<T>>
/**
* Find multiple models instance using a key/value pair
*/