ReviewOS

also looking at this

loghqorg/loghq

Deploy: uniform auth session model (main → production)

#7
Merged glennmichael123 wants to merge main into production
282 files +3028 -64856
docs/basics/models.mddeleted+0-735
Changes to docs/basics/models.md
@@ -1,735 +0,0 @@
1---
2title: Models
3description: Learn how to define and use ORM models in Stacks applications
4---
5
6attributes: {
7 name: {
8 factory: faker => faker.person.fullName(),
9 },
10
11 email: {
12 factory: faker => faker.internet.email(),
13 },
14
15 status: {
16 factory: faker => faker.helpers.arrayElement(['active', 'inactive', 'pending']),
17 },
18
19 // Factory with access to other attributes
20 slug: {
21 factory: (faker, attributes) => {
22 const name = attributes?.name || faker.lorem.word()
23 return name.toLowerCase().replace(/\s+/g, '-')
24 },
25 },
26}
27
28```
29
30## Relationships
31
32### Has One
33
34Define a one-to-one relationship:
35
36```typescript
37
38// app/Models/User.ts
39export default {
40 name: 'User',
41 table: 'users',
42
43 hasOne: ['Profile'],
44
45 // Or with configuration
46 hasOne: [
47 {
48 model: 'Profile',
49 foreignKey: 'user_id',
50 relationName: 'profile',
51 },
52 ],
53} satisfies Model
54
55```
56
57### Has Many
58
59Define a one-to-many relationship:
60
61```typescript
62
63// app/Models/User.ts
64export default {
65 name: 'User',
66 table: 'users',
67
68 hasMany: ['Post', 'Comment'],
69
70 // Or with configuration
71 hasMany: [
72 {
73 model: 'Post',
74 foreignKey: 'author_id',
75 relationName: 'posts',
76 },
77 {
78 model: 'Comment',
79 foreignKey: 'user_id',
80 },
81 ],
82} satisfies Model
83
84```
85
86### Belongs To
87
88Define an inverse one-to-many relationship:
89
90```typescript
91
92// app/Models/Post.ts
93export default {
94 name: 'Post',
95 table: 'posts',
96
97 belongsTo: ['User'],
98
99 // Or with configuration
100 belongsTo: [
101 {
102 model: 'User',
103 foreignKey: 'author_id',
104 relationName: 'author',
105 },
106 ],
107} satisfies Model
108
109```
110
111### Belongs To Many
112
113Define a many-to-many relationship:
114
115```typescript
116
117// app/Models/Post.ts
118export default {
119 name: 'Post',
120 table: 'posts',
121
122 belongsToMany: ['Tag'],
123
124 // With pivot table configuration
125 belongsToMany: [
126 {
127 model: 'Tag',
128 pivotTable: 'post_tags',
129 firstForeignKey: 'post_id',
130 secondForeignKey: 'tag_id',
131 },
132 ],
133} satisfies Model
134
135```
136
137### Has One Through
138
139Define a has-one-through relationship:
140
141```typescript
142
143// app/Models/Country.ts
144export default {
145 name: 'Country',
146 table: 'countries',
147
148 hasOneThrough: [
149 {
150 model: 'Capital',
151 through: 'State',
152 throughForeignKey: 'country_id',
153 relationName: 'capital',
154 },
155 ],
156} satisfies Model
157
158```
159
160### Polymorphic Relationships (Morph)
161
162Define polymorphic relationships:
163
164```typescript
165
166// app/Models/Comment.ts
167export default {
168 name: 'Comment',
169 table: 'comments',
170
171 morphOne: {
172 model: 'Image',
173 morphName: 'imageable',
174 type: 'imageable_type',
175 id: 'imageable_id',
176 },
177} satisfies Model
178
179```
180
181## Traits
182
183### Available Traits
184
185```typescript
186
187traits: {
188 // Timestamps (created_at, updated_at)
189 useTimestamps: true,
190
191 // UUID column
192 useUuid: true,
193
194 // Soft deletes (deleted_at)
195 useSoftDeletes: true,
196
197 // Observable (emit events on changes)
198 observe: true,
199
200 // Searchable (Algolia/MeiliSearch integration)
201 searchable: true,
202
203 // Billable (Stripe integration)
204 billable: true,
205
206 // Auto-generate API routes
207 useApi: {
208 uri: 'posts',
209 routes: ['index', 'store', 'show', 'update', 'destroy'],
210 middleware: ['auth'],
211 },
212
213 // Seeder configuration
214 useSeeder: {
215 count: 50,
216 },
217}
218
219```
220
221### API Trait Configuration
222
223Generate RESTful API routes automatically:
224
225```typescript
226
227traits: {
228 useApi: {
229 // Base URI for routes
230 uri: 'posts',
231
232 // Routes to generate
233 routes: ['index', 'store', 'show', 'update', 'destroy'],
234
235 // Or with custom action paths
236 routes: {
237 index: 'PostIndexAction',
238 store: 'PostStoreAction',
239 show: 'PostShowAction',
240 update: 'PostUpdateAction',
241 destroy: 'PostDestroyAction',
242 },
243
244 // Middleware for all routes
245 middleware: ['auth', 'throttle:60,1'],
246 },
247}
248
249```
250
251This generates:
252
253- `GET /posts` - List posts
254- `POST /posts` - Create post
255- `GET /posts/{id}` - Show post
256- `PATCH /posts/{id}` - Update post
257- `DELETE /posts/{id}` - Delete post
258
259## Querying Models
260
261### Basic Queries
262
263```typescript
264
265import { Post } from '@stacksjs/orm'
266
267// Find by ID
268const post = await Post.find(1)
269
270// Find or fail
271const post = await Post.findOrFail(1)
272
273// Get all records
274const posts = await Post.all()
275
276// First record
277const post = await Post.first()
278
279// Last record
280const post = await Post.last()
281
282```
283
284### Where Clauses
285
286```typescript
287
288// Simple where
289const posts = await Post.where('status', 'published').get()
290
291// With operator
292const posts = await Post.where('views', '>', 100).get()
293
294// Multiple conditions
295const posts = await Post
296 .where('status', 'published')
297 .where('author_id', 1)
298 .get()
299
300// Or where
301const posts = await Post
302 .where('status', 'published')
303 .orWhere([['status', 'draft'], ['author_id', 1]])
304 .get()
305
306// Where in
307const posts = await Post.whereIn('id', [1, 2, 3]).get()
308
309// Where not in
310const posts = await Post.whereNotIn('status', ['archived', 'deleted']).get()
311
312// Where null
313const posts = await Post.whereNull('deleted_at').get()
314
315// Where not null
316const posts = await Post.whereNotNull('published_at').get()
317
318// Where between
319const posts = await Post.whereBetween('created_at', ['2024-01-01', '2024-12-31']).get()
320
321// Where like
322const posts = await Post.whereLike('title', '%TypeScript%').get()
323
324```
325
326### Ordering and Limiting
327
328```typescript
329
330// Order by
331const posts = await Post.orderBy('created_at', 'desc').get()
332
333// Order by shortcuts
334const posts = await Post.orderByDesc('created_at').get()
335const posts = await Post.orderByAsc('title').get()
336
337// Latest/Oldest
338const latestPost = await Post.latest('created_at')
339const oldestPost = await Post.oldest('created_at')
340
341// Random order
342const posts = await Post.inRandomOrder().get()
343
344// Limit and offset
345const posts = await Post.take(10).skip(20).get()
346
347```
348
349### Selecting Columns
350
351```typescript
352
353// Select specific columns
354const posts = await Post.select(['id', 'title', 'created_at']).get()
355
356// Distinct values
357const statuses = await Post.distinct('status').get()
358
359```
360
361### Aggregates
362
363```typescript
364
365// Count
366const total = await Post.count()
367
368// Max
369const maxViews = await Post.max('views')
370
371// Min
372const minViews = await Post.min('views')
373
374// Average
375const avgViews = await Post.avg('views')
376
377// Sum
378const totalViews = await Post.sum('views')
379
380```
381
382### Pagination
383
384```typescript
385
386const result = await Post.paginate({
387 page: 1,
388 limit: 15,
389})
390
391// Result shape:
392// {
393// data: Post[],
394// paging: {
395// total_records: number,
396// page: number,
397// total_pages: number,
398// },
399// next_cursor: number | null,
400// }
401
402```
403
404### Eager Loading
405
406```typescript
407
408// Load relationships
409const posts = await Post.with(['author', 'comments']).get()
410
411// Nested relationships
412const posts = await Post.with(['author', 'comments.user']).get()
413
414```
415
416### Chunking
417
418Process large datasets efficiently:
419
420```typescript
421
422await Post.chunk(100, async (posts) => {
423 for (const post of posts) {
424 await processPost(post)
425 }
426})
427
428```
429
430## Creating and Updating
431
432### Creating Records
433
434```typescript
435
436// Create single record
437const post = await Post.create({
438 title: 'Hello World',
439 content: 'This is my first post',
440 status: 'draft',
441})
442
443// Create multiple records
444await Post.createMany([
445 { title: 'Post 1', content: 'Content 1' },
446 { title: 'Post 2', content: 'Content 2' },
447])
448
449// First or create
450const post = await Post.firstOrCreate(
451 { email: 'user@example.com' }, // Search criteria
452 { name: 'New User' }, // Values to create with
453)
454
455// Update or create
456const post = await Post.updateOrCreate(
457 { email: 'user@example.com' }, // Search criteria
458 { name: 'Updated Name' }, // Values to update/create with
459)
460
461```
462
463### Updating Records
464
465```typescript
466
467// Update single record
468const post = await Post.find(1)
469await post.update({ title: 'Updated Title' })
470
471// Save changes
472post.title = 'New Title'
473await post.save()
474
475// Force update (bypass guarded)
476await post.forceUpdate({ admin_only_field: 'value' })
477
478```
479
480### Deleting Records
481
482```typescript
483
484// Delete single record
485const post = await Post.find(1)
486await post.delete()
487
488// Delete by ID
489await Post.remove(1)
490
491```
492
493## Scopes
494
495### Local Scopes
496
497Define reusable query constraints:
498
499```typescript
500
501// In your model usage
502const publishedPosts = await Post
503 .where('status', 'published')
504 .where('published_at', '<=', new Date())
505 .get()
506
507// Create a helper function
508async function getPublishedPosts() {
509 return Post
510 .where('status', 'published')
511 .whereNotNull('published_at')
512 .orderByDesc('published_at')
513 .get()
514}
515
516```
517
518### Conditional Queries
519
520```typescript
521
522const posts = await Post
523 .when(request.has('category'), (query) => {
524 return query.where('category_id', request.get('category'))
525 })
526 .when(request.has('search'), (query) => {
527 return query.whereLike('title', `%${request.get('search')}%`)
528 })
529 .get()
530
531```
532
533## Events
534
535### Model Observers
536
537Enable model events with the `observe` trait:
538
539```typescript
540
541traits: {
542 observe: true,
543}
544
545```
546
547This emits events on model changes:
548
549- `{model}:created` - After creation
550- `{model}:updated` - After update
551- `{model}:deleted` - After deletion
552
553### Listening to Events
554
555```typescript
556
557import { events } from '@stacksjs/events'
558
559events.on('post:created', async (post) => {
560 console.log('New post created:', post.title)
561 await notifySubscribers(post)
562})
563
564events.on('post:updated', async (post) => {
565 await invalidateCache(`post:${post.id}`)
566})
567
568events.on('post:deleted', async (post) => {
569 await cleanupRelatedData(post.id)
570})
571
572```
573
574## Soft Deletes
575
576### Enabling Soft Deletes
577
578```typescript
579
580traits: {
581 useSoftDeletes: true,
582}
583
584```
585
586This adds a `deleted_at` column and modifies query behavior.
587
588### Querying with Soft Deletes
589
590```typescript
591
592// Normal queries exclude soft-deleted records
593const posts = await Post.all()
594
595// Include soft-deleted records
596const allPosts = await Post.withTrashed().get()
597
598// Only soft-deleted records
599const trashedPosts = await Post.onlyTrashed().get()
600
601// Restore soft-deleted record
602const post = await Post.withTrashed().find(1)
603await post.restore()
604
605// Permanently delete
606await post.forceDelete()
607
608```
609
610## JSON Serialization
611
612### Hiding Attributes
613
614```typescript
615
616attributes: {
617 password: {
618 hidden: true, // Never included in JSON
619 fillable: true,
620 validation: {
621 rule: schema.string().min(8),
622 },
623 },
624}
625
626```
627
628### Converting to JSON
629
630```typescript
631
632const post = await Post.find(1)
633
634// Get JSON representation
635const json = post.toJSON()
636
637// Includes all visible attributes and loaded relationships
638
639```
640
641## Edge Cases and Gotchas
642
643### Mass Assignment Protection
644
645Attributes must be marked as `fillable` for mass assignment:
646
647```typescript
648
649// This works
650const post = await Post.create({
651 title: 'Hello', // fillable: true
652 content: 'World', // fillable: true
653})
654
655// This field is ignored
656const post = await Post.create({
657 admin_only: true, // fillable: false (ignored)
658})
659
660// Use forceCreate to bypass
661const post = await Post.forceCreate({
662 admin_only: true, // Works with forceCreate
663})
664
665```
666
667### Relationship Loading
668
669Always use `.with()` for eager loading to avoid N+1 queries:
670
671```typescript
672
673// Bad: N+1 queries
674const posts = await Post.all()
675for (const post of posts) {
676 console.log(post.author.name) // Query per post!
677}
678
679// Good: Eager loading
680const posts = await Post.with(['author']).get()
681for (const post of posts) {
682 console.log(post.author.name) // Already loaded
683}
684
685```
686
687### Transaction Support
688
689```typescript
690
691import { transaction } from '@stacksjs/database'
692
693await transaction(async (trx) => {
694 const user = await User.create({ name: 'John' }, { transaction: trx })
695 await Post.create({ title: 'Hello', author_id: user.id }, { transaction: trx })
696 // Both operations commit or rollback together
697})
698
699```
700
701## API Reference
702
703### Model Instance Methods
704
705| Method | Description |
706|--------|-------------|
707| `save()` | Save changes to database |
708| `update(data)` | Update with new data |
709| `forceUpdate(data)` | Update bypassing guarded |
710| `delete()` | Delete the record |
711| `toJSON()` | Convert to JSON object |
712| `toSearchableObject()` | Convert for search indexing |
713
714### Static Query Methods
715
716| Method | Description |
717|--------|-------------|
718| `find(id)` | Find by primary key |
719| `findOrFail(id)` | Find or throw error |
720| `findMany(ids)` | Find multiple by IDs |
721| `all()` | Get all records |
722| `first()` | Get first record |
723| `last()` | Get last record |
724| `create(data)` | Create new record |
725| `createMany(data[])` | Create multiple records |
726| `where(column, value)` | Add where clause |
727| `with(relations)` | Eager load relationships |
728| `paginate(options)` | Paginate results |
729
730## Related Documentation
731
732- [Database](/features/database) - Database configuration
733- [Migrations](/features/migrations) - Database migrations
734- [Validation](/packages/validation) - Validation rules
735- [Actions](/basics/actions) - Using models in actions