Skip to content

Commit bd77c56

Browse files
author
FreedomKnight
committed
spreate hasCategoies into strict and normal
1 parent b77a2db commit bd77c56

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/Categorizable.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,13 @@ public function recategorize(...$categories): self
3737
}
3838

3939
public function scopeHasCategories(Builder $builder, ...$categories): Builder
40+
{
41+
return $builder->whereHas('categories', function (Builder $query) use ($categories) {
42+
$query->whereIn('category_id', Category::descendantsAndSelf($this->normalize($categories))->pluck('id'));
43+
});
44+
}
45+
46+
public function scopeHasStrictCategories(Builder $builder, ...$categories): Builder
4047
{
4148
return $builder->whereHas('categories', function (Builder $query) use ($categories) {
4249
$query->whereIn('category_id', $this->normalize($categories));

tests/CategoryTest.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,12 +173,22 @@ public function testRemoveCategory()
173173
]);
174174
}
175175

176-
public function testFindModelHasCategories()
176+
public function testFindModelHasStrictCategories()
177177
{
178178
$category = Category::create(['name' => 'News']);
179179
$thing = TestModel::create(['title' => 'foo']);
180180
$thing->categorize($category->id);
181181

182+
$this->assertCount(1, TestModel::hasStrictCategories('News')->get());
183+
}
184+
185+
public function testFindModelHasCategories()
186+
{
187+
$parent = Category::create(['name' => 'News']);
188+
$child = Category::create(['name' => 'HeadLine', 'parent_id' => $parent->id]);
189+
$thing = TestModel::create(['title' => 'foo']);
190+
$thing->categorize($child->id);
191+
182192
$this->assertCount(1, TestModel::hasCategories('News')->get());
183193
}
184194

0 commit comments

Comments
 (0)