Skip to content

Commit 03cb3f8

Browse files
author
oleksandrb
committed
Add hasColumn method
1 parent d66f46b commit 03cb3f8

File tree

2 files changed

+45
-5
lines changed

2 files changed

+45
-5
lines changed

src/Schema/Builder.php

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace MongoDB\Laravel\Schema;
66

77
use Closure;
8+
use Illuminate\Support\Facades\DB;
89
use MongoDB\Model\CollectionInfo;
910

1011
use function count;
@@ -13,15 +14,37 @@
1314

1415
class Builder extends \Illuminate\Database\Schema\Builder
1516
{
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
1825
{
19-
return true;
26+
$collection = $this->connection->table($table);
27+
28+
return $collection->where($column, 'exists', true)
29+
->project(['_id' => 1])
30+
->exists();
2031
}
2132

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
2442
{
43+
foreach ($columns as $column) {
44+
if (!$this->hasColumn($table, $column)) {
45+
return false;
46+
}
47+
}
2548
return true;
2649
}
2750

tests/SchemaTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,23 @@ public function testRenameColumn(): void
377377
$this->assertSame($check[2]['column'], $check2[2]['column']);
378378
}
379379

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+
380397
protected function getIndex(string $collection, string $name)
381398
{
382399
$collection = DB::getCollection($collection);

0 commit comments

Comments
 (0)