Skip to content

Commit

Permalink
Allow custom tag table name and primary key for scoped queries (#529)
Browse files Browse the repository at this point in the history
* Added customizable tag table and primary key through config file

* updated default config file

* removed redundant config options

* Update HasTags.php

---------

Co-authored-by: Freek Van der Herten <[email protected]>
  • Loading branch information
gtmassey and freekmurze authored Jan 31, 2025
1 parent c0ac810 commit 73ef478
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions src/HasTags.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,24 @@ public static function getTagClassName(): string
return config('tags.tag_model', Tag::class);
}

public static function getTagTableName(): string
{
$tagInstance = new (self::getTagClassName());

return $tagInstance->getTable();
}

public static function getTagTablePrimaryKeyName(): string
{
return self::getTagTableName() . '.' . self::getTagPrimaryKey();
}

public static function getTagPrimaryKey(): string
{
$tagInstance = new (self::getTagClassName());
return $tagInstance->getKeyName();
}

public function getTaggableMorphName(): string
{
return config('tags.taggable.morph_name', 'taggable');
Expand Down Expand Up @@ -95,7 +113,7 @@ public function scopeWithAllTags(

collect($tags)->each(function ($tag) use ($query) {
$query->whereHas('tags', function (Builder $query) use ($tag) {
$query->where('tags.id', $tag->id ?? 0);
$query->where(self::getTagTablePrimaryKeyName(), $tag->id ?? 0);
});
});

Expand All @@ -113,7 +131,7 @@ public function scopeWithAnyTags(
->whereHas('tags', function (Builder $query) use ($tags) {
$tagIds = collect($tags)->pluck('id');

$query->whereIn('tags.id', $tagIds);
$query->whereIn(self::getTagTablePrimaryKeyName(), $tagIds);
});
}

Expand All @@ -128,7 +146,7 @@ public function scopeWithoutTags(
->whereDoesntHave('tags', function (Builder $query) use ($tags) {
$tagIds = collect($tags)->pluck('id');

$query->whereIn('tags.id', $tagIds);
$query->whereIn(self::getTagTablePrimaryKeyName(), $tagIds);
});
}

Expand All @@ -140,7 +158,7 @@ public function scopeWithAllTagsOfAnyType(Builder $query, $tags): Builder
->each(function ($tag) use ($query) {
$query->whereHas(
'tags',
fn (Builder $query) => $query->where('tags.id', $tag ? $tag->id : 0)
fn (Builder $query) => $query->where(self::getTagTablePrimaryKeyName(), $tag ? $tag->id : 0)
);
});

Expand All @@ -155,7 +173,7 @@ public function scopeWithAnyTagsOfAnyType(Builder $query, $tags): Builder

return $query->whereHas(
'tags',
fn (Builder $query) => $query->whereIn('tags.id', $tagIds)
fn (Builder $query) => $query->whereIn(self::getTagTablePrimaryKeyName(), $tagIds)
);
}

Expand Down

0 comments on commit 73ef478

Please sign in to comment.