Skip to content

Commit 35e6ab7

Browse files
authored
Merge pull request #1 from binafy/add-getReactionsWithCount-method
Add `getReactionsWithCount` method to Reactable
2 parents c307486 + dde8615 commit 35e6ab7

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

src/Traits/Reactable.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,20 @@ public function getReactCountByType(string|LaravelReactionTypeEnum $type): int
7575
return $this->reactions()->where('type', $type)->count();
7676
}
7777

78-
// Attributes
78+
/**
79+
* Get reactions with count.
80+
*/
81+
public function getReactionsWithCount(): \Illuminate\Support\Collection
82+
{
83+
return $this
84+
->reactions()
85+
->groupBy('type')
86+
->selectRaw('type, count(id) as total')
87+
->get()
88+
->mapWithKeys(fn (Reaction $reaction) => [$reaction->type => $reaction->total]);
89+
}
7990

91+
// Attributes
8092

8193
/**
8294
* Get is_reacted attribute.

tests/Feature/CountReactionTest.php

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
<?php
22

33
use Binafy\LaravelReaction\Enums\LaravelReactionTypeEnum;
4-
use Binafy\LaravelReaction\Models\Reaction;
54
use Tests\SetUp\Models\Post;
65
use Tests\SetUp\Models\User;
6+
use function PHPUnit\Framework\assertEquals;
77

88
test('get react count by type', function () {
99
$user = User::query()->first();
@@ -16,8 +16,32 @@
1616
$user2 = User::query()->create(['name' => 'test', 'email' => '[email protected]', 'password' => bcrypt(12345)]);
1717
$post->reaction(LaravelReactionTypeEnum::REACTION_CLAP->value, $user2);
1818

19-
\PHPUnit\Framework\assertEquals(
19+
assertEquals(
2020
$post->getReactCountByType(LaravelReactionTypeEnum::REACTION_CLAP->value),
2121
2
2222
);
2323
});
24+
25+
test('getReactionsWithCount method work correctly', function () {
26+
$user = User::query()->first();
27+
$user2 = User::query()->create([
28+
'name' => 'User 2',
29+
'email' => '[email protected]',
30+
'password' => bcrypt(123456),
31+
]);
32+
$user3 = User::query()->create([
33+
'name' => 'User 3',
34+
'email' => '[email protected]',
35+
'password' => bcrypt(123456),
36+
]);
37+
$post = Post::query()->first();
38+
39+
$post->reaction(LaravelReactionTypeEnum::REACTION_CLAP->value, $user);
40+
$post->reaction(LaravelReactionTypeEnum::REACTION_CLAP->value, $user2);
41+
$post->reaction(LaravelReactionTypeEnum::REACTION_CLAP->value, $user3);
42+
43+
assertEquals(
44+
$post->getReactionsWithCount()->toArray(),
45+
[LaravelReactionTypeEnum::REACTION_CLAP->value => 3],
46+
);
47+
});

0 commit comments

Comments
 (0)