-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforge-sql-orm.html
More file actions
1540 lines (1324 loc) · 71.7 KB
/
forge-sql-orm.html
File metadata and controls
1540 lines (1324 loc) · 71.7 KB
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
<!DOCTYPE html>
<html lang="en" class="scroll-smooth">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forge Kernel - ForgeSqlOrm</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/docs.css">
</head>
<body class="bg-gray-50 text-gray-900">
<!-- Navigation -->
<nav class="bg-white shadow-sm border-b">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex items-center">
<div class="flex-shrink-0">
<h1 class="text-xl font-bold text-gray-900">
Forge Kernel
</h1>
</div>
<div class="hidden sm:ml-6 sm:flex sm:space-x-8">
<a href="index.html"
class="text-gray-900 inline-flex items-center px-1 pt-1 text-sm font-medium hover:text-blue-600">
Home
</a>
<a href="getting-started.html"
class="text-gray-900 inline-flex items-center px-1 pt-1 text-sm font-medium hover:text-blue-600">
Getting Started
</a>
<a href="core-concepts.html"
class="text-gray-900 inline-flex items-center px-1 pt-1 text-sm font-medium hover:text-blue-600">
Core Concepts
</a>
<a href="modules.html"
class="text-blue-600 inline-flex items-center px-1 pt-1 text-sm font-medium border-b-2 border-blue-600">
Capabilities
</a>
<a href="api-reference.html"
class="text-gray-900 inline-flex items-center px-1 pt-1 text-sm font-medium hover:text-blue-600">
API Reference
</a>
<a href="tutorial.html"
class="text-gray-900 inline-flex items-center px-1 pt-1 text-sm font-medium hover:text-blue-600">
Tutorials
</a>
</div>
</div>
<div class="flex items-center sm:hidden">
<button id="mobile-menu-button" class="text-gray-700 hover:text-blue-600 p-2">
<i class="fas fa-bars text-xl"></i>
</button>
</div>
</div>
</div>
<div id="mobile-menu" class="sm:hidden hidden bg-white border-t border-gray-200">
<div class="px-2 pt-2 pb-3 space-y-1">
<a href="index.html" class="block px-3 py-2 text-gray-900 hover:text-blue-600">Home</a>
<a href="getting-started.html" class="block px-3 py-2 text-gray-900 hover:text-blue-600">Getting Started</a>
<a href="core-concepts.html" class="block px-3 py-2 text-gray-900 hover:text-blue-600">Core Concepts</a>
<a href="modules.html" class="block px-3 py-2 text-blue-600 font-medium">Capabilities</a>
<a href="api-reference.html" class="block px-3 py-2 text-gray-900 hover:text-blue-600">API Reference</a>
<a href="tutorial.html" class="block px-3 py-2 text-gray-900 hover:text-blue-600">Tutorials</a>
</div>
</div>
</nav>
<!-- Main Content -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div class="flex flex-col lg:flex-row gap-8">
<!-- Sidebar Navigation -->
<div id="sidebar-nav" class="lg:w-1/4">
<div class="bg-white rounded-lg shadow-sm p-6 sticky top-8">
<h3 class="text-lg font-semibold text-gray-900 mb-4">ForgeSqlOrm</h3>
<nav class="space-y-2">
<a href="#overview" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Overview</a>
<a href="#architecture" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Architecture & Design</a>
<a href="#installation" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Installation</a>
<a href="#models-overview" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Models Overview</a>
<a href="#model-attributes" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Model Attributes</a>
<a href="#creating-models" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Creating Models</a>
<a href="#model-operations" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Model Operations</a>
<a href="#query-builder" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">QueryBuilder</a>
<a href="#model-query" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">ModelQuery</a>
<a href="#relationships" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Relationships</a>
<a href="#type-casting" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Type Casting</a>
<a href="#traits" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Traits</a>
<a href="#soft-deletes" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Soft Deletes</a>
<a href="#protected-hidden" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Protected & Hidden Fields</a>
<a href="#repository-pattern" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Repository Pattern</a>
<a href="#query-caching" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Query Caching</a>
<a href="#transactions" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Transactions</a>
<a href="#raw-sql" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Raw SQL Queries</a>
<a href="#examples" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Usage Examples</a>
<a href="#best-practices" class="nav-link block px-3 py-2 text-sm text-gray-700 rounded-md hover:text-blue-600">Best Practices</a>
</nav>
</div>
</div>
<!-- Main Content -->
<div class="lg:w-3/4">
<div class="bg-white rounded-lg shadow-sm p-8">
<h1 class="text-4xl font-bold text-gray-900 mb-6">ForgeSqlOrm</h1>
<p class="text-xl text-gray-600 mb-8">
SQL ORM support for Forge Kernel. Provides attribute-based models, fluent query builder, relationships, repository pattern, query caching, and full transaction support for SQLite, MySQL, and PostgreSQL.
</p>
<!-- Overview -->
<section id="overview" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Overview</h2>
<p class="text-gray-600 mb-6">
ForgeSqlOrm provides comprehensive Object-Relational Mapping (ORM) support for Forge Kernel applications. It offers model-based database access, fluent query builder, relationship support, repository pattern, and query caching.
</p>
<div class="bg-blue-50 border border-blue-200 rounded-lg p-6 mb-6">
<h3 class="font-semibold text-lg mb-4">Key Features</h3>
<div class="grid md:grid-cols-2 gap-4">
<div class="space-y-2">
<div class="flex items-center"><span>Attribute-based model definition</span></div>
<div class="flex items-center"><span>Fluent query builder (immutable)</span></div>
<div class="flex items-center"><span>Relationship support (HasOne, HasMany, BelongsTo)</span></div>
<div class="flex items-center"><span>Eager and lazy loading</span></div>
</div>
<div class="space-y-2">
<div class="flex items-center"><span>Repository pattern with caching</span></div>
<div class="flex items-center"><span>Automatic type casting</span></div>
<div class="flex items-center"><span>Soft deletes support</span></div>
<div class="flex items-center"><span>Full transaction support</span></div>
</div>
</div>
</div>
<h3 class="text-lg font-semibold mb-3">What ForgeSqlOrm Provides</h3>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li><strong>Model-Based ORM:</strong> Clean, attribute-based model definition with automatic property mapping</li>
<li><strong>Fluent Query Builder:</strong> Immutable, chainable query builder implementing QueryBuilderInterface</li>
<li><strong>Relationship Support:</strong> HasOne, HasMany, BelongsTo relationships with eager/lazy loading</li>
<li><strong>Type Casting:</strong> Automatic casting with DTO and enum support</li>
<li><strong>Repository Pattern:</strong> Clean data access layer with built-in caching</li>
<li><strong>Query Caching:</strong> Built-in caching for performance optimization</li>
<li><strong>Transaction Support:</strong> Full transaction support via QueryBuilder</li>
<li><strong>Soft Deletes:</strong> Soft delete support with onlyTrashed() queries</li>
<li><strong>Traits:</strong> HasTimeStamps and HasMetaData for common functionality</li>
</ul>
<div class="bg-green-50 border-l-4 border-green-400 p-4 mb-6">
<p class="text-sm text-green-700">
<strong>Core Module:</strong> ForgeSqlOrm is a core module (type: 'core', order: 1), providing essential ORM functionality for Forge Kernel applications. It depends on ForgeDatabaseSql for database connectivity.
</p>
</div>
</section>
<!-- Architecture & Design -->
<section id="architecture" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Architecture & Design Philosophy</h2>
<p class="text-gray-600 mb-6">
ForgeSqlOrm is built with clean architecture, performance, and developer experience in mind.
</p>
<h3 class="text-lg font-semibold mb-3">Model-Based ORM Approach</h3>
<p class="text-gray-600 mb-4">
ForgeSqlOrm uses a model-based approach:
</p>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li>Models extend the base Model class</li>
<li>Attribute-based definition using PHP 8 attributes</li>
<li>Automatic property mapping from database rows</li>
<li>Type casting on model hydration</li>
<li>Automatic timestamps and soft delete support</li>
</ul>
<h3 class="text-lg font-semibold mb-3">Fluent Query Builder Pattern</h3>
<p class="text-gray-600 mb-4">
QueryBuilder implements an immutable, fluent interface:
</p>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li>Immutable pattern — each method returns a new instance</li>
<li>Chainable methods for building complex queries</li>
<li>Implements QueryBuilderInterface for dependency injection</li>
<li>Parameter binding for SQL injection prevention</li>
<li>Support for raw SQL when needed</li>
</ul>
<h3 class="text-lg font-semibold mb-3">Repository Pattern for Data Access</h3>
<p class="text-gray-600 mb-4">
Repository pattern provides clean data access:
</p>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li>Repository interface for common operations</li>
<li>RecordRepository base class with CRUD operations</li>
<li>QueryCache integration for performance</li>
<li>Cache invalidation on create/update/delete</li>
<li>Custom find methods with caching</li>
</ul>
<h3 class="text-lg font-semibold mb-3">Relationship Eager/Lazy Loading</h3>
<p class="text-gray-600 mb-4">
Efficient relationship loading:
</p>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li>Eager loading with with() method to prevent N+1 queries</li>
<li>Lazy loading with load() method for on-demand loading</li>
<li>RelationLoader for efficient batch loading</li>
<li>Nested relationship support</li>
</ul>
</section>
<!-- Installation -->
<section id="installation" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Installation</h2>
<p class="text-gray-600 mb-6">
ForgeSqlOrm is a core module and is typically available by default. It can also be installed via ForgePackageManager.
</p>
<h3 class="text-lg font-semibold mb-3">Using ForgePackageManager</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-bash"># Install with wizard (interactive)
php forge.php package:install-module
# Install directly (skip wizard)
php forge.php package:install-module --module=ForgeSqlOrm
# Install specific version
php forge.php package:install-module --module=ForgeSqlOrm@0.1.8</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Dependency</h3>
<p class="text-gray-600 mb-4">
ForgeSqlOrm depends on ForgeDatabaseSql for database connectivity. Ensure ForgeDatabaseSql is installed and configured.
</p>
<h3 class="text-lg font-semibold mb-3">Container Bindings</h3>
<p class="text-gray-600 mb-4">
The module automatically registers QueryBuilderInterface and QueryCache:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">public function register(Container $container): void
{
// Bind QueryBuilderInterface to QueryBuilder
$container->bind(QueryBuilderInterface::class, function ($c) {
return new QueryBuilder($c->get(DatabaseConnectionInterface::class));
});
// Register QueryCache as singleton
$container->singleton(QueryCache::class, function () {
return new QueryCache(3600); // TTL: 3600 seconds
});
}</code></pre>
</div>
</section>
<!-- Models Overview -->
<section id="models-overview" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Models Overview</h2>
<p class="text-gray-600 mb-6">
Models in ForgeSqlOrm extend the base Model class and use attributes to define their structure.
</p>
<h3 class="text-lg font-semibold mb-3">Model Characteristics</h3>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li><strong>Extend Model:</strong> All models extend the abstract Model base class</li>
<li><strong>Attribute-Based:</strong> Use #[Table] and #[Column] attributes for definition</li>
<li><strong>Automatic Property Mapping:</strong> Properties are automatically mapped from database rows</li>
<li><strong>Type Casting:</strong> Automatic casting on model hydration using Cast enum</li>
<li><strong>Timestamps Support:</strong> Use HasTimeStamps trait for automatic created_at/updated_at</li>
<li><strong>Soft Deletes:</strong> Built-in soft delete support with deleted_at column</li>
<li><strong>Protected Fields:</strong> Use #[ProtectedFields] to exclude fields from serialization</li>
<li><strong>Hidden Fields:</strong> Use #[Hidden] to hide fields from toArray()/JSON</li>
</ul>
<h3 class="text-lg font-semibold mb-3">Model Lifecycle</h3>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li><strong>Hydration:</strong> Models are created from database rows using fromRow()</li>
<li><strong>Saving:</strong> save() method inserts new records or updates existing ones</li>
<li><strong>Deletion:</strong> delete() method performs soft delete (or force delete if soft deletes disabled)</li>
<li><strong>Serialization:</strong> toArray() and jsonSerialize() respect protected/hidden fields</li>
</ul>
</section>
<!-- Model Attributes -->
<section id="model-attributes" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Model Attributes</h2>
<p class="text-gray-600 mb-6">
ForgeSqlOrm uses PHP 8 attributes to define model structure and behavior.
</p>
<h3 class="text-lg font-semibold mb-3">#[Table]</h3>
<p class="text-gray-600 mb-4">
Define the database table name for the model:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[Table("users")]
class User extends Model
{
// ...
}</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">#[Column]</h3>
<p class="text-gray-600 mb-4">
Define a column with type casting:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[Column(primary: true, cast: Cast::INT)]
public int $id;
#[Column(cast: Cast::STRING)]
public string $email;
#[Column(cast: Cast::JSON)]
public ?UserMetadataDto $metadata;</code></pre>
</div>
<p class="text-gray-600 mb-4">
Column attributes support:
</p>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li><strong>primary:</strong> Mark as primary key</li>
<li><strong>cast:</strong> Cast enum value for automatic type casting</li>
</ul>
<h3 class="text-lg font-semibold mb-3">#[ProtectedFields]</h3>
<p class="text-gray-600 mb-4">
Exclude fields from toArray() and JSON serialization:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[ProtectedFields(['password'])]
class User extends Model
{
#[Column(cast: Cast::STRING)]
public string $password; // Excluded from toArray()/JSON
}</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">#[Hidden]</h3>
<p class="text-gray-600 mb-4">
Hide a field from serialization:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[Hidden]
#[Column(cast: Cast::STRING)]
public string $internal_field; // Hidden from toArray()/JSON</code></pre>
</div>
</section>
<!-- Creating Models -->
<section id="creating-models" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Creating Models</h2>
<p class="text-gray-600 mb-6">
Models are defined by extending the Model base class and using attributes.
</p>
<h3 class="text-lg font-semibold mb-3">Basic Model Structure</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">use App\Modules\ForgeSqlOrm\ORM\Attributes\Table;
use App\Modules\ForgeSqlOrm\ORM\Attributes\Column;
use App\Modules\ForgeSqlOrm\ORM\Model;
use App\Modules\ForgeSqlOrm\ORM\Values\Cast;
#[Table("users")]
class User extends Model
{
#[Column(primary: true, cast: Cast::INT)]
public int $id;
#[Column(cast: Cast::STRING)]
public string $email;
}</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Model with Traits</h3>
<p class="text-gray-600 mb-4">
Use traits for common functionality:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">use App\Modules\ForgeSqlOrm\Traits\HasTimeStamps;
use App\Modules\ForgeSqlOrm\Traits\HasMetaData;
#[Table("profiles")]
class Profile extends Model
{
use HasTimeStamps; // Adds created_at, updated_at
use HasMetaData; // Adds metadata JSON column
#[Column(primary: true, cast: Cast::INT)]
public int $id;
}</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Model with Relationships</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">use App\Modules\ForgeSqlOrm\ORM\Values\Relate;
use App\Modules\ForgeSqlOrm\ORM\Values\RelationKind;
#[Table("users")]
class User extends Model
{
use HasTimeStamps;
use CanLoadRelations;
#[Column(primary: true, cast: Cast::INT)]
public int $id;
#[Relate(RelationKind::HasOne, Profile::class, "user_id")]
public function profile(): Relation
{
return self::describe(__FUNCTION__);
}
}</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Model with Protected Fields</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[Table("users")]
#[ProtectedFields(['password'])]
class User extends Model
{
#[Column(cast: Cast::STRING)]
public string $password; // Excluded from toArray()/JSON
}</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Model with Tenant Scoping</h3>
<p class="text-gray-600 mb-4">
Models can integrate with ForgeMultiTenant:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">use App\Modules\ForgeMultiTenant\Attributes\TenantScoped;
use App\Modules\ForgeMultiTenant\Traits\TenantScopedTrait;
#[TenantScoped]
#[Table("posts")]
class Post extends Model
{
use HasTimeStamps;
use HasMetaData;
use TenantScopedTrait;
#[Column(primary: true, cast: Cast::STRING)]
public int $id;
#[Column(cast: Cast::STRING)]
public string $tenant_id;
}</code></pre>
</div>
</section>
<!-- Model Operations -->
<section id="model-operations" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Model Operations</h2>
<p class="text-gray-600 mb-6">
Models provide methods for creating, updating, deleting, and querying records.
</p>
<h3 class="text-lg font-semibold mb-3">save()</h3>
<p class="text-gray-600 mb-4">
Insert a new record or update an existing one:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">$user = new User();
$user->email = 'user@example.com';
$user->password = 'hashed_password';
$user->save(); // Inserts new record
$user->email = 'newemail@example.com';
$user->save(); // Updates existing record</code></pre>
</div>
<p class="text-gray-600 mb-4">
The save() method:
</p>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li>Automatically detects if record exists (checks primary key)</li>
<li>Inserts new records or updates existing ones</li>
<li>Automatically sets created_at and updated_at if HasTimeStamps trait is used</li>
<li>Generates UUID primary keys if needed</li>
</ul>
<h3 class="text-lg font-semibold mb-3">delete()</h3>
<p class="text-gray-600 mb-4">
Soft delete or force delete a record:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">$user = User::query()->id(1)->first();
$user->delete(); // Soft delete (sets deleted_at)
// Force delete (if soft deletes disabled)
$user->forceDelete();</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">toArray()</h3>
<p class="text-gray-600 mb-4">
Convert model to array (respects protected fields):
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">$user = User::query()->id(1)->first();
$array = $user->toArray(); // Excludes protected fields</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">jsonSerialize()</h3>
<p class="text-gray-600 mb-4">
JSON serialization (respects protected fields):
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">$user = User::query()->id(1)->first();
$json = json_encode($user); // Uses jsonSerialize()</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">fromRow()</h3>
<p class="text-gray-600 mb-4">
Create model instance from database row:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">$row = ['id' => 1, 'email' => 'user@example.com'];
$user = User::fromRow($row); // Creates User instance with type casting</code></pre>
</div>
</section>
<!-- QueryBuilder -->
<section id="query-builder" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">QueryBuilder</h2>
<p class="text-gray-600 mb-6">
QueryBuilder provides a fluent, immutable interface for building database queries.
</p>
<h3 class="text-lg font-semibold mb-3">Basic Query Methods</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">use App\Modules\ForgeSqlOrm\ORM\QueryBuilder;
use Forge\Core\Contracts\Database\QueryBuilderInterface;
// Inject QueryBuilderInterface
public function __construct(
private readonly QueryBuilderInterface $builder
) {}
// Basic query
$results = $this->builder
->table('users')
->where('status', '=', 'active')
->orderBy('created_at', 'DESC')
->limit(10)
->get();</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Where Clauses</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Simple where
$results = $this->builder->table('users')
->where('email', '=', 'user@example.com')
->get();
// Where with IN
$results = $this->builder->table('users')
->whereIn('id', [1, 2, 3])
->get();
// Where with NOT IN
$results = $this->builder->table('users')
->whereNotIn('status', ['deleted', 'banned'])
->get();
// Where NULL
$results = $this->builder->table('users')
->whereNull('deleted_at')
->get();
// Where NOT NULL
$results = $this->builder->table('users')
->whereNotNull('email')
->get();</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Select Specific Columns</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">$results = $this->builder->table('users')
->select('id', 'email', 'identifier')
->where('status', '=', 'active')
->get();</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Ordering and Pagination</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">$results = $this->builder->table('users')
->orderBy('created_at', 'DESC')
->limit(10)
->offset(20)
->get();</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Aggregate Functions</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Count
$count = $this->builder->table('users')
->where('status', '=', 'active')
->count();
// Sum
$total = $this->builder->table('orders')
->sum('amount');
// Average
$avg = $this->builder->table('orders')
->avg('amount');
// Min/Max
$min = $this->builder->table('orders')->min('amount');
$max = $this->builder->table('orders')->max('amount');</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">CRUD Operations</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Insert
$id = $this->builder->table('users')
->insert(['email' => 'user@example.com', 'password' => 'hash']);
// Update
$this->builder->table('users')
->where('id', '=', 1)
->update(['email' => 'newemail@example.com']);
// Delete
$this->builder->table('users')
->where('id', '=', 1)
->delete();</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Locking</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">$results = $this->builder->table('users')
->where('id', '=', 1)
->lockForUpdate()
->get();</code></pre>
</div>
</section>
<!-- ModelQuery -->
<section id="model-query" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">ModelQuery</h2>
<p class="text-gray-600 mb-6">
ModelQuery provides a model-specific query builder that returns Model instances.
</p>
<h3 class="text-lg font-semibold mb-3">Basic Usage</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Get all users
$users = User::query()->get();
// Get first user
$user = User::query()->first();
// Find by ID
$user = User::query()->id(1)->first();</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Where Clauses</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Where clause
$users = User::query()
->where('status', '=', 'active')
->get();
// Where NULL
$users = User::query()
->whereNull('deleted_at')
->get();</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Soft Deletes</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Only trashed (soft deleted)
$deletedUsers = User::query()->onlyTrashed()->get();
// Soft delete
$user = User::query()->id(1)->first();
$user->softDelete();
// Force delete
User::query()->id(1)->forceDelete();</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Eager Loading</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Eager load relationships
$users = User::query()
->with('profile')
->get();
// Nested relationships
$users = User::query()
->with('profile', 'posts')
->get();</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">CRUD Operations</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Insert
User::query()->insert(['email' => 'user@example.com']);
// Update
User::query()
->where('id', '=', 1)
->update(['email' => 'newemail@example.com']);</code></pre>
</div>
</section>
<!-- Relationships -->
<section id="relationships" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Relationships</h2>
<p class="text-gray-600 mb-6">
ForgeSqlOrm supports three types of relationships: HasOne, HasMany, and BelongsTo.
</p>
<h3 class="text-lg font-semibold mb-3">Defining Relationships</h3>
<p class="text-gray-600 mb-4">
Use the #[Relate] attribute to define relationships:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">use App\Modules\ForgeSqlOrm\ORM\Values\Relate;
use App\Modules\ForgeSqlOrm\ORM\Values\RelationKind;
#[Table("users")]
class User extends Model
{
use CanLoadRelations;
// HasOne relationship
#[Relate(RelationKind::HasOne, Profile::class, "user_id")]
public function profile(): Relation
{
return self::describe(__FUNCTION__);
}
// HasMany relationship
#[Relate(RelationKind::HasMany, Post::class, "user_id")]
public function posts(): Relation
{
return self::describe(__FUNCTION__);
}
}
#[Table("posts")]
class Post extends Model
{
// BelongsTo relationship
#[Relate(RelationKind::BelongsTo, User::class, "user_id")]
public function user(): Relation
{
return self::describe(__FUNCTION__);
}
}</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Eager Loading</h3>
<p class="text-gray-600 mb-4">
Eager loading prevents N+1 queries:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Eager load relationships
$users = User::query()
->with('profile')
->get();
// Access relationship
foreach ($users as $user) {
$profile = $user->profile; // Already loaded, no query
}</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Lazy Loading</h3>
<p class="text-gray-600 mb-4">
Lazy loading loads relationships on demand:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">$user = User::query()->id(1)->first();
$user->load('profile'); // Loads profile relationship</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Nested Relationships</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Load nested relationships
$users = User::query()
->with('profile', 'posts')
->get();</code></pre>
</div>
</section>
<!-- Type Casting -->
<section id="type-casting" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Type Casting</h2>
<p class="text-gray-600 mb-6">
ForgeSqlOrm automatically casts database values to PHP types using the Cast enum.
</p>
<h3 class="text-lg font-semibold mb-3">Cast Enum Values</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">enum Cast: string
{
case INT = "int";
case FLOAT = "float";
case BOOL = "bool";
case STRING = "string";
case JSON = "json";
case DATE = "date";
case DATETIME = "datetime";
case TIMESTAMP = "timestamp";
case ENUM = "enum";
}</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Using Cast in Models</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[Table("users")]
class User extends Model
{
#[Column(primary: true, cast: Cast::INT)]
public int $id;
#[Column(cast: Cast::STRING)]
public string $email;
#[Column(cast: Cast::JSON)]
public ?UserMetadataDto $metadata; // Casts to DTO
#[Column(cast: Cast::DATETIME)]
public ?DateTimeImmutable $created_at;
}</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">DTO Support</h3>
<p class="text-gray-600 mb-4">
JSON columns can be cast to DTOs:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[Column(cast: Cast::JSON)]
public ?UserMetadataDto $metadata;
// Automatically casts JSON string to UserMetadataDto instance
// when loading from database</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Enum Support</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[Column(cast: Cast::ENUM)]
public ?UserStatus $status; // BackedEnum instance</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Date Types</h3>
<p class="text-gray-600 mb-4">
Date types are cast to DateTimeImmutable:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[Column(cast: Cast::DATE)]
public ?DateTimeImmutable $birth_date;
#[Column(cast: Cast::DATETIME)]
public ?DateTimeImmutable $created_at;
#[Column(cast: Cast::TIMESTAMP)]
public ?DateTimeImmutable $updated_at;</code></pre>
</div>
</section>
<!-- Traits -->
<section id="traits" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Traits</h2>
<p class="text-gray-600 mb-6">
ForgeSqlOrm provides traits for common model functionality.
</p>
<h3 class="text-lg font-semibold mb-3">HasTimeStamps</h3>
<p class="text-gray-600 mb-4">
Automatically adds created_at and updated_at columns:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">use App\Modules\ForgeSqlOrm\Traits\HasTimeStamps;
#[Table("users")]
class User extends Model
{
use HasTimeStamps;
// Automatically adds:
// public ?DateTimeImmutable $created_at = null;
// public ?DateTimeImmutable $updated_at = null;
}</code></pre>
</div>
<p class="text-gray-600 mb-4">
The save() method automatically sets these timestamps:
</p>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">
<li>created_at is set on insert</li>
<li>updated_at is set on insert and update</li>
</ul>
<h3 class="text-lg font-semibold mb-3">HasMetaData</h3>
<p class="text-gray-600 mb-4">
Automatically adds a metadata JSON column:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">use App\Modules\ForgeSqlOrm\Traits\HasMetaData;
#[Table("profiles")]
class Profile extends Model
{
use HasMetaData;
// Automatically adds:
// public ?array $metadata = null;
}</code></pre>
</div>
</section>
<!-- Soft Deletes -->
<section id="soft-deletes" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Soft Deletes</h2>
<p class="text-gray-600 mb-6">
ForgeSqlOrm supports soft deletes, allowing records to be marked as deleted without actually removing them from the database.
</p>
<h3 class="text-lg font-semibold mb-3">Soft Delete Column</h3>
<p class="text-gray-600 mb-4">
Models use a deleted_at column (configurable via SOFT_DELETE_COLUMN constant):
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Default soft delete column
protected const string SOFT_DELETE_COLUMN = 'deleted_at';</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Soft Deleting Records</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">$user = User::query()->id(1)->first();
$user->delete(); // Sets deleted_at timestamp</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Querying Soft Deleted Records</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Only trashed (soft deleted) records
$deletedUsers = User::query()->onlyTrashed()->get();
// Normal queries exclude soft deleted records
$activeUsers = User::query()->get(); // Excludes soft deleted</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Force Delete</h3>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">// Force delete (permanently remove)
$user = User::query()->id(1)->first();
$user->forceDelete();
// Or via ModelQuery
User::query()->id(1)->forceDelete();</code></pre>
</div>
</section>
<!-- Protected & Hidden Fields -->
<section id="protected-hidden" class="section-anchor mb-12">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Protected & Hidden Fields</h2>
<p class="text-gray-600 mb-6">
ForgeSqlOrm provides two ways to exclude fields from serialization: protected fields and hidden fields.
</p>
<h3 class="text-lg font-semibold mb-3">Protected Fields</h3>
<p class="text-gray-600 mb-4">
Use #[ProtectedFields] to exclude fields from toArray() and JSON serialization:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[Table("users")]
#[ProtectedFields(['password'])]
class User extends Model
{
#[Column(cast: Cast::STRING)]
public string $password; // Excluded from toArray()/JSON
}
$user = User::query()->id(1)->first();
$array = $user->toArray(); // password is excluded
$json = json_encode($user); // password is excluded</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Hidden Fields</h3>
<p class="text-gray-600 mb-4">
Use #[Hidden] attribute on individual fields:
</p>
<div class="code-block p-6 text-white rounded-lg mb-6">
<pre><code class="language-php">#[Table("users")]
class User extends Model
{
#[Hidden]
#[Column(cast: Cast::STRING)]
public string $internal_field; // Hidden from toArray()/JSON
}</code></pre>
</div>
<h3 class="text-lg font-semibold mb-3">Use Cases</h3>
<ul class="list-disc list-inside space-y-2 text-gray-600 mb-4">