Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/Phaseolies/Database/Entity/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2986,6 +2986,28 @@ public function repair(callable $fixer, bool $saveChanges = false): Collection
return $results;
}

/**
* Get records grouped by a callback result
*
* @param callable $callback
* @return array
*/
public function groupByCallback(callable $callback): array
{
$results = $this->get();
$grouped = [];

foreach ($results as $item) {
$key = $callback($item);
if (!isset($grouped[$key])) {
$grouped[$key] = [];
}
$grouped[$key][] = $item;
}

return $grouped;
}

/**
* Convert camelCase to snake_case for column names
*
Expand Down
30 changes: 30 additions & 0 deletions tests/Model/Query/EntityModelQueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Tests\Unit\Model\Query;

use App\Models\Product;
use Tests\Support\Model\MockUser;
use Tests\Support\Model\MockTag;
use Tests\Support\Model\MockPost;
Expand Down Expand Up @@ -2661,4 +2662,33 @@ public function testRepairMethodSaveChanges()
$this->assertNull($product->price);
}
}

public function testGroupByCallback()
{
$products = MockProduct::groupByCallback(function ($product) {
if ($product->price < 500) return 'lower_than_500';
if ($product->price > 500) return 'bigger_than_500';
return 'default';
});

$this->assertCount(1, $products['lower_than_500']);

foreach ($products['lower_than_500'] as $key => $product) {
$this->assertEquals(
435,
$product->price,
"Expected product ID {$product->id} to have price 435"
);
}

$this->assertCount(2, $products['bigger_than_500']);

foreach ($products['bigger_than_500'] as $product) {
$this->assertGreaterThan(
500,
$product->price,
"Expected product ID {$product->id} to have price > 500"
);
}
}
}
Loading