87 lines
2.5 KiB
PHP
87 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
class MusicSubcategory extends Model
|
|
{
|
|
protected $table = 'music_subcategories';
|
|
|
|
protected $fillable = [
|
|
'category_id', 'name', 'slug', 'description', 'image_id', 'order', 'is_active'
|
|
];
|
|
|
|
protected $casts = [
|
|
'is_active' => 'boolean',
|
|
'order' => 'integer',
|
|
];
|
|
|
|
public function category(): BelongsTo
|
|
{
|
|
return $this->belongsTo(MusicCategory::class, 'category_id');
|
|
}
|
|
|
|
public function playlists(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(MusicPlaylist::class, 'music_subcategory_playlist', 'subcategory_id', 'playlist_id');
|
|
}
|
|
|
|
public function image(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Image::class);
|
|
}
|
|
|
|
public function getActivePlaylistsAttribute()
|
|
{
|
|
return $this->playlists()->where('music_playlists.is_active', true)->orderBy('music_playlists.order')->get();
|
|
}
|
|
|
|
// Get total music count across all playlists in this subcategory
|
|
public function getTotalMusicCountAttribute()
|
|
{
|
|
return $this->playlists()
|
|
->withCount('musics')
|
|
->get()
|
|
->sum('musics_count');
|
|
}
|
|
|
|
// Get total duration across all music in this subcategory
|
|
public function getTotalDurationAttribute()
|
|
{
|
|
$totalSeconds = 0;
|
|
foreach ($this->playlists as $playlist) {
|
|
foreach ($playlist->musics as $music) {
|
|
$totalSeconds += $this->durationToSeconds($music->duration);
|
|
}
|
|
}
|
|
return $this->secondsToDuration($totalSeconds);
|
|
}
|
|
|
|
private function durationToSeconds($duration)
|
|
{
|
|
if (!$duration) return 0;
|
|
$parts = explode(':', $duration);
|
|
if (count($parts) === 2) {
|
|
return (int)$parts[0] * 60 + (int)$parts[1];
|
|
} elseif (count($parts) === 3) {
|
|
return (int)$parts[0] * 3600 + (int)$parts[1] * 60 + (int)$parts[2];
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
private function secondsToDuration($seconds)
|
|
{
|
|
$hours = floor($seconds / 3600);
|
|
$minutes = floor(($seconds % 3600) / 60);
|
|
$secs = $seconds % 60;
|
|
|
|
if ($hours > 0) {
|
|
return sprintf("%d:%02d:%02d", $hours, $minutes, $secs);
|
|
}
|
|
return sprintf("%d:%02d", $minutes, $secs);
|
|
}
|
|
}
|