File tree Expand file tree Collapse file tree 3 files changed +63
-0
lines changed Expand file tree Collapse file tree 3 files changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ declare (strict_types=1 );
4
+
5
+ namespace MongoDB \Laravel \Eloquent ;
6
+
7
+ trait HasDocumentVersion
8
+ {
9
+ /**
10
+ * Auto call on model instance as booting
11
+ *
12
+ * @return void
13
+ */
14
+ public static function bootHasDocumentVersion (): void
15
+ {
16
+ static ::saving (function ($ model ) {
17
+ $ versionKey = static ::getDocumentVersionKey ();
18
+ if (!empty ($ versionKey )) {
19
+ $ model ->{$ versionKey } = defined (static ::class.'::DOCUMENT_VERSION ' )
20
+ ? (int ) static ::DOCUMENT_VERSION
21
+ : 1 ;
22
+ }
23
+ });
24
+ }
25
+
26
+ /**
27
+ * Get document version key
28
+ *
29
+ * @return string
30
+ */
31
+ protected static function getDocumentVersionKey (): string
32
+ {
33
+ return defined (static ::class.'::DOCUMENT_VERSION_KEY ' )
34
+ ? (string ) static ::DOCUMENT_VERSION_KEY
35
+ : '__v ' ;
36
+ }
37
+ }
Original file line number Diff line number Diff line change 19
19
use MongoDB \Laravel \Connection ;
20
20
use MongoDB \Laravel \Eloquent \Model ;
21
21
use MongoDB \Laravel \Tests \Models \Book ;
22
+ use MongoDB \Laravel \Tests \Models \DocumentVersion ;
22
23
use MongoDB \Laravel \Tests \Models \Guarded ;
23
24
use MongoDB \Laravel \Tests \Models \IdIsBinaryUuid ;
24
25
use MongoDB \Laravel \Tests \Models \IdIsInt ;
@@ -53,6 +54,7 @@ public function tearDown(): void
53
54
Book::truncate ();
54
55
Item::truncate ();
55
56
Guarded::truncate ();
57
+ DocumentVersion::truncate ();
56
58
}
57
59
58
60
public function testNewModel (): void
@@ -1188,6 +1190,12 @@ public function testCreateWithNullId()
1188
1190
$ this ->assertSame (1 , User::count ());
1189
1191
}
1190
1192
1193
+ public function testDocumentVersion ()
1194
+ {
1195
+ $ document = DocumentVersion::create (['name ' => 'versionTest ' ]);
1196
+ $ this ->assertEquals (1 , $ document ->__v );
1197
+ }
1198
+
1191
1199
/** @param class-string<Model> $modelClass */
1192
1200
private static function registerModelEvents (string $ modelClass , array &$ events ): void
1193
1201
{
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ declare (strict_types=1 );
4
+
5
+ namespace MongoDB \Laravel \Tests \Models ;
6
+
7
+ use MongoDB \Laravel \Eloquent \HasDocumentVersion ;
8
+ use MongoDB \Laravel \Eloquent \Model as Eloquent ;
9
+
10
+ /** @property int __v */
11
+ class DocumentVersion extends Eloquent
12
+ {
13
+ use HasDocumentVersion;
14
+
15
+ protected $ connection = 'mongodb ' ;
16
+ protected $ collection = 'documentVersion ' ;
17
+ protected static $ unguarded = true ;
18
+ }
You can’t perform that action at this time.
0 commit comments