File tree Expand file tree Collapse file tree 2 files changed +45
-5
lines changed Expand file tree Collapse file tree 2 files changed +45
-5
lines changed Original file line number Diff line number Diff line change 5
5
namespace MongoDB \Laravel \Schema ;
6
6
7
7
use Closure ;
8
+ use Illuminate \Support \Facades \DB ;
8
9
use MongoDB \Model \CollectionInfo ;
9
10
10
11
use function count ;
13
14
14
15
class Builder extends \Illuminate \Database \Schema \Builder
15
16
{
16
- /** @inheritdoc */
17
- public function hasColumn ($ table , $ column )
17
+ /**
18
+ * Check if column exists in the collection schema.
19
+ *
20
+ * @param $table
21
+ * @param $column
22
+ * @return bool
23
+ */
24
+ public function hasColumn ($ table , $ column ): bool
18
25
{
19
- return true ;
26
+ $ collection = $ this ->connection ->table ($ table );
27
+
28
+ return $ collection ->where ($ column , 'exists ' , true )
29
+ ->project (['_id ' => 1 ])
30
+ ->exists ();
20
31
}
21
32
22
- /** @inheritdoc */
23
- public function hasColumns ($ table , array $ columns )
33
+ /**
34
+ * Check if columns exists in the collection schema.
35
+ *
36
+ * @param $table
37
+ * @param array $columns
38
+ *
39
+ * @return bool
40
+ */
41
+ public function hasColumns ($ table , array $ columns ): bool
24
42
{
43
+ foreach ($ columns as $ column ) {
44
+ if (!$ this ->hasColumn ($ table , $ column )) {
45
+ return false ;
46
+ }
47
+ }
25
48
return true ;
26
49
}
27
50
Original file line number Diff line number Diff line change @@ -377,6 +377,23 @@ public function testRenameColumn(): void
377
377
$ this ->assertSame ($ check [2 ]['column ' ], $ check2 [2 ]['column ' ]);
378
378
}
379
379
380
+ public function testHasColumn (): void
381
+ {
382
+ DB ::connection ()->collection ('newcollection ' )->insert (['column1 ' => 'value ' ]);
383
+
384
+ $ this ->assertTrue (Schema::hasColumn ('newcollection ' , 'column1 ' ));
385
+ $ this ->assertFalse (Schema::hasColumn ('newcollection ' , 'column2 ' ));
386
+ }
387
+
388
+ public function testHasColumns (): void
389
+ {
390
+ DB ::connection ()->collection ('newcollection ' )->insert (['column1 ' => 'value ' ]);
391
+ DB ::connection ()->collection ('newcollection ' )->insert (['column2 ' => 'value ' ]);
392
+
393
+ $ this ->assertTrue (Schema::hasColumns ('newcollection ' , ['column1 ' , 'column2 ' ]));
394
+ $ this ->assertFalse (Schema::hasColumns ('newcollection ' , ['column1 ' , 'column3 ' ]));
395
+ }
396
+
380
397
protected function getIndex (string $ collection , string $ name )
381
398
{
382
399
$ collection = DB ::getCollection ($ collection );
You can’t perform that action at this time.
0 commit comments