From 1b1260becefa996960594fd60464b448922188ad Mon Sep 17 00:00:00 2001 From: "Christopher C. Wells" Date: Fri, 26 Feb 2021 09:26:31 -0800 Subject: [PATCH] Add convenience method to get total tags figures per model --- app/Models/Traits/Ingredient.php | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) 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(); + } }