diff --git a/app/Models/Traits/Ingredient.php b/app/Models/Traits/Ingredient.php index 67e4d4b..f50c3c4 100644 --- a/app/Models/Traits/Ingredient.php +++ b/app/Models/Traits/Ingredient.php @@ -3,8 +3,10 @@ namespace App\Models\Traits; use App\Models\IngredientAmount; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Relations\MorphMany; -use Illuminate\Support\Collection; +use Illuminate\Support\Facades\DB; +use Spatie\Tags\Tag; trait Ingredient { @@ -30,4 +32,25 @@ trait Ingredient public function ingredientAmountRelationships(): MorphMany { return $this->morphMany(IngredientAmount::class, 'ingredient')->with('parent'); } + + /** + * Get totals for all tags used by the ingredient. + * + * This method assumes the ingredient has the `HasTags` trait. + * + * @see \Spatie\Tags\HasTags + */ + public static function getTagTotals(string $locale = null): Collection { + $locale = $locale ?? app()->getLocale(); + return Tag::query()->join('taggables', 'taggables.tag_id', '=', 'id') + ->select([ + 'id', + "name->{$locale} as name", + DB::raw('count(*) as total') + ]) + ->where('taggables.taggable_type', '=', static::class) + ->groupBy('id') + ->orderBy("name->{$locale}") + ->get(); + } }