0
# Model Definition and Querying
1
2
Core model functionality for defining database entities, validation, and basic CRUD operations.
3
4
## Capabilities
5
6
### Model Class
7
8
Base class for creating database models with validation, relationships, and query capabilities.
9
10
```javascript { .api }
11
/**
12
* Base Model class for database entities
13
*/
14
class Model {
15
// Static configuration properties
16
static get tableName(): string;
17
static get idColumn(): string | string[];
18
static get jsonSchema(): object;
19
static get relationMappings(): object;
20
static get jsonAttributes(): string[];
21
static get virtualAttributes(): string[];
22
static get modifiers(): object;
23
24
// Static query methods
25
static query(trx?: Transaction): QueryBuilder;
26
static relatedQuery(relationName: string, trx?: Transaction): QueryBuilder;
27
28
// Static factory methods
29
static fromJson(json: object, options?: ModelOptions): Model;
30
static fromDatabaseJson(json: object): Model;
31
32
// Static transaction methods
33
static transaction<T>(callback: (trx: Transaction) => Promise<T>): Promise<T>;
34
static bindKnex(knex: Knex): typeof Model;
35
36
// Instance methods
37
$id(id?: any): any;
38
$query(trx?: Transaction): QueryBuilder;
39
$relatedQuery(relationName: string, trx?: Transaction): QueryBuilder;
40
41
// JSON conversion
42
$toJson(options?: ToJsonOptions): object;
43
$toDatabaseJson(): object;
44
$setJson(json: object, options?: ModelOptions): this;
45
$setDatabaseJson(json: object): this;
46
47
// Validation
48
$validate(json?: object, options?: ModelOptions): object;
49
$beforeValidate(jsonSchema: object, json: object, options: ModelOptions): object;
50
$afterValidate(json: object, options: ModelOptions): void;
51
52
// Relations
53
$fetchGraph(expression: RelationExpression, options?: FetchGraphOptions): Promise<this>;
54
$setRelated(relation: string, related: Model | Model[]): this;
55
$appendRelated(relation: string, related: Model | Model[]): this;
56
57
// Lifecycle hooks
58
$beforeInsert(queryContext: QueryContext): Promise<void> | void;
59
$afterInsert(queryContext: QueryContext): Promise<void> | void;
60
$beforeUpdate(options: ModelOptions, queryContext: QueryContext): Promise<void> | void;
61
$afterUpdate(options: ModelOptions, queryContext: QueryContext): Promise<void> | void;
62
$beforeDelete(queryContext: QueryContext): Promise<void> | void;
63
$afterDelete(queryContext: QueryContext): Promise<void> | void;
64
65
// Utility methods
66
$clone(options?: CloneOptions): this;
67
$traverse(traverser: TraverserFunction): this;
68
$knex(): Knex;
69
}
70
```
71
72
**Usage Examples:**
73
74
```javascript
75
const { Model } = require('objection');
76
77
// Define a model
78
class Person extends Model {
79
static get tableName() {
80
return 'persons';
81
}
82
83
static get idColumn() {
84
return 'id';
85
}
86
87
static get jsonSchema() {
88
return {
89
type: 'object',
90
required: ['firstName', 'lastName'],
91
properties: {
92
id: { type: 'integer' },
93
firstName: { type: 'string', minLength: 1, maxLength: 255 },
94
lastName: { type: 'string', minLength: 1, maxLength: 255 },
95
age: { type: 'integer', minimum: 0, maximum: 200 },
96
email: { type: 'string', format: 'email' }
97
}
98
};
99
}
100
101
static get relationMappings() {
102
return {
103
pets: {
104
relation: Model.HasManyRelation,
105
modelClass: Pet,
106
join: {
107
from: 'persons.id',
108
to: 'pets.ownerId'
109
}
110
}
111
};
112
}
113
114
// Instance methods
115
fullName() {
116
return `${this.firstName} ${this.lastName}`;
117
}
118
}
119
120
// Create instances
121
const person = Person.fromJson({
122
firstName: 'John',
123
lastName: 'Doe',
124
age: 25
125
});
126
127
// Validate
128
const validated = person.$validate();
129
```
130
131
### Static Query Methods
132
133
Methods for creating query builders at the model class level.
134
135
```javascript { .api }
136
/**
137
* Create a QueryBuilder for this model
138
* @param trx - Optional transaction or knex instance
139
* @returns QueryBuilder instance
140
*/
141
static query(trx?: Transaction): QueryBuilder;
142
143
/**
144
* Create a QueryBuilder for a related model
145
* @param relationName - Name of the relation
146
* @param trx - Optional transaction or knex instance
147
* @returns QueryBuilder instance
148
*/
149
static relatedQuery(relationName: string, trx?: Transaction): QueryBuilder;
150
```
151
152
### Instance Query Methods
153
154
Methods for creating query builders at the model instance level.
155
156
```javascript { .api }
157
/**
158
* Create a QueryBuilder for this model instance
159
* @param trx - Optional transaction or knex instance
160
* @returns QueryBuilder instance
161
*/
162
$query(trx?: Transaction): QueryBuilder;
163
164
/**
165
* Create a QueryBuilder for a related model of this instance
166
* @param relationName - Name of the relation
167
* @param trx - Optional transaction or knex instance
168
* @returns QueryBuilder instance
169
*/
170
$relatedQuery(relationName: string, trx?: Transaction): QueryBuilder;
171
```
172
173
### JSON Conversion Methods
174
175
Methods for converting between JSON and model instances.
176
177
```javascript { .api }
178
/**
179
* Convert model to JSON object
180
* @param options - Conversion options
181
* @returns Plain object representation
182
*/
183
$toJson(options?: ToJsonOptions): object;
184
185
/**
186
* Convert model to database JSON format
187
* @returns Database-formatted object
188
*/
189
$toDatabaseJson(): object;
190
191
/**
192
* Set model properties from JSON
193
* @param json - JSON object to set
194
* @param options - Model options
195
* @returns This model instance
196
*/
197
$setJson(json: object, options?: ModelOptions): this;
198
199
/**
200
* Create model instance from JSON
201
* @param json - JSON object
202
* @param options - Model options
203
* @returns New model instance
204
*/
205
static fromJson(json: object, options?: ModelOptions): Model;
206
```
207
208
### ID Management
209
210
Methods for getting and setting model IDs.
211
212
```javascript { .api }
213
/**
214
* Get or set the model's ID
215
* @param id - Optional ID to set
216
* @returns Current ID or void if setting
217
*/
218
$id(id?: any): any;
219
220
/**
221
* Check if model has an ID
222
* @returns True if model has ID
223
*/
224
$hasId(): boolean;
225
```
226
227
### Model Configuration
228
229
Static properties for configuring model behavior.
230
231
```javascript { .api }
232
// Table name for the model
233
static get tableName(): string;
234
235
// Primary key column(s)
236
static get idColumn(): string | string[];
237
238
// JSON Schema for validation
239
static get jsonSchema(): object;
240
241
// Relationship mappings
242
static get relationMappings(): object;
243
244
// Columns that contain JSON data
245
static get jsonAttributes(): string[];
246
247
// Virtual attributes (not persisted)
248
static get virtualAttributes(): string[];
249
250
// Query modifiers
251
static get modifiers(): object;
252
253
// Column name mappers
254
static get columnNameMappers(): ColumnNameMappers;
255
```
256
257
## Types
258
259
```typescript { .api }
260
interface ModelOptions {
261
patch?: boolean;
262
skipValidation?: boolean;
263
old?: object;
264
}
265
266
interface ToJsonOptions {
267
virtuals?: boolean | string[];
268
shallow?: boolean;
269
}
270
271
interface CloneOptions {
272
shallow?: boolean;
273
}
274
275
interface FetchGraphOptions {
276
transaction?: Transaction;
277
skipFetched?: boolean;
278
}
279
280
interface TraverserFunction {
281
(model: Model, parentModel?: Model, relationName?: string): void;
282
}
283
284
interface QueryContext {
285
transaction?: Transaction;
286
[key: string]: any;
287
}
288
289
interface ColumnNameMappers {
290
parse(json: object): object;
291
format(json: object): object;
292
}
293
```