. */ namespace Poniverse\Ponyfm; use DB; use Illuminate\Database\Eloquent\Relations\Relation; use Poniverse\Ponyfm\Traits\SlugTrait; use Illuminate\Database\Eloquent\Model; use URL; use Venturecraft\Revisionable\RevisionableTrait; class Genre extends Model { protected $table = 'genres'; protected $fillable = ['name', 'slug']; protected $appends = ['track_count', 'url']; protected $hidden = ['trackCountRelation']; public $timestamps = false; use SlugTrait, RevisionableTrait; public function tracks(){ return $this->hasMany(Track::class, 'genre_id'); } /** * "Dummy" relation to facilitate eager-loading of a genre's track count. * This relationship should not be used directly. * * Inspired by {@link http://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/} * * @return Relation */ public function trackCountRelation() { return $this->hasOne(Track::class) ->select(['genre_id', DB::raw('count(*) as track_count')]) ->groupBy('genre_id'); } /** * Returns the number of tracks in this genre. * * @return int */ public function getTrackCountAttribute() { if (!$this->relationLoaded('trackCountRelation')) { $this->load('trackCountRelation'); } return $this->trackCountRelation ? $this->trackCountRelation->track_count : 0; } /** * @return string relative, Angular-friendly URL to this genre */ public function getUrlAttribute() { return URL::route('tracks.discover', ['filter' => "genres-{$this->id}"], false); } }