Add convenience method to get total tags figures per model

This commit is contained in:
Christopher C. Wells 2021-02-26 09:26:31 -08:00 committed by Christopher Charbonneau Wells
parent f747c0f191
commit 1b1260bece
1 changed files with 24 additions and 1 deletions

View File

@ -3,8 +3,10 @@
namespace App\Models\Traits; namespace App\Models\Traits;
use App\Models\IngredientAmount; use App\Models\IngredientAmount;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB;
use Spatie\Tags\Tag;
trait Ingredient trait Ingredient
{ {
@ -30,4 +32,25 @@ trait Ingredient
public function ingredientAmountRelationships(): MorphMany { public function ingredientAmountRelationships(): MorphMany {
return $this->morphMany(IngredientAmount::class, 'ingredient')->with('parent'); 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();
}
} }