Skip to content

Commit

Permalink
Add support for groupBy
Browse files Browse the repository at this point in the history
  • Loading branch information
imanghafoori1 committed Jun 21, 2023
1 parent 7e44327 commit 3cee9c1
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/FakeDB.php
Original file line number Diff line number Diff line change
Expand Up @@ -442,13 +442,21 @@ public static function filter($query, $columns = ['*']): Collection
{
$orderBy = $query->orders;
$selects = $query->columns;
$groups = $query->groups;
$offset = $query->offset;
$limit = $query->limit;
$from = $query->from;
$joins = $query->joins ?? [];
$base = FakeDB::$fakeRows[$from] ?? [];
$collection = FakeDB::performJoins($base, $joins);

if ($groups) {
foreach ($groups as &$group) {
$group = $from.'.'.$group;
}
$collection = $collection->groupBy($groups);
}

foreach ($orderBy ?: [] as $i => $_order) {
if (isset($_order['column'])) {
$orderBy[$i]['column'] = FakeDB::prefixColumn($_order['column'], $from, $joins);
Expand Down
45 changes: 45 additions & 0 deletions tests/GroupByTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace Imanghafoori\EloquentMockery\Tests;

use Illuminate\Database\Eloquent\Model;
use Imanghafoori\EloquentMockery\FakeDB;
use PHPUnit\Framework\TestCase;

class GroupByModel extends Model
{
protected $table = 'my_tbl';
}

class GroupByTest extends TestCase
{
public function setUp(): void
{
FakeDB::mockQueryBuilder();
}

public function tearDown(): void
{
FakeDB::dontMockQueryBuilder();
}

/**
* @test
*/
public function groupByBasicTest()
{
FakeDB::addRow('my_tbl', ['id' => 1,'col1' => 'v1']);
FakeDB::addRow('my_tbl', ['id' => 2,'col1' => 'v2']);
FakeDB::addRow('my_tbl', ['id' => 3,'col1' => 'v1']);
FakeDB::addRow('my_tbl', ['id' => 4,'col1' => 'v3']);
FakeDB::addRow('my_tbl', ['id' => 5,'col1' => 'v2']);

$rows = GroupByModel::query()->groupBy('col1')->get();

$this->assertCount(3, $rows);

$this->assertEquals(3, $rows[0]->id);
$this->assertEquals(5, $rows[1]->id);
$this->assertEquals(4, $rows[2]->id);
}
}

0 comments on commit 3cee9c1

Please sign in to comment.