KTV/app/Models/Song.php

95 lines
2.9 KiB
PHP
Raw Permalink Normal View History

2025-04-25 09:33:28 +08:00
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Helpers\ChineseNameConverter;
use App\Helpers\ChineseStrokesConverter;
2025-05-12 14:13:56 +08:00
use App\Traits\LogsModelActivity;
2025-04-25 09:33:28 +08:00
class Song extends Model
{
/** @use HasFactory<\Database\Factories\SongFactory> */
2025-05-12 14:13:56 +08:00
use HasFactory, LogsModelActivity;
2025-04-25 09:33:28 +08:00
protected $fillable = [
'id',
2025-04-25 09:33:28 +08:00
'name',
'adddate',
'filename',
'language_type',
'db_change',
'vocal',
'situation',
'copyright01',
'copyright02',
'note01',
'note02',
'note03',
'note04',
'enable',
'simplified',
'phonetic_abbr',
'pinyin_abbr',
'strokes_abbr',
'song_number',
2025-05-05 16:54:21 +08:00
'song_counts',
2025-04-25 09:33:28 +08:00
];
protected function casts(): array
{
return [
'vocal' => 'boolean',
'enable' => 'boolean',
'language_type' => \App\Enums\SongLanguageType::class,
'situation' => \App\Enums\SongSituation::class,
];
}
2025-04-25 09:33:28 +08:00
public function users(){
return $this->belongsToMany(User::class, 'user_song')->withTimestamps();
}
2025-04-25 18:21:20 +08:00
public function str_artists(){
return $this->artists->pluck('name')->implode(', ');
}
2025-04-25 09:33:28 +08:00
public function artists(){
return $this->belongsToMany(Artist::class);
}
2025-04-25 18:21:20 +08:00
public function str_categories(){
return $this->categories->pluck('name')->implode(', ');
}
2025-04-25 09:33:28 +08:00
public function categories(){
return $this->belongsToMany(SongCategory::class);
}
public function branches(){
return $this->belongsToMany(Branch::class)
->withPivot('counts')
->withTimestamps();
}
2025-04-25 09:33:28 +08:00
protected static function booted()
{
// 無論是 creating 或 updating都執行這段共用的邏輯
2025-05-14 15:32:54 +08:00
static::saving(function (Song $song) {
2025-04-25 09:33:28 +08:00
$simplified=ChineseNameConverter::convertToSimplified($song->name);// 繁體轉簡體
$song->simplified = $simplified;
$song->phonetic_abbr = ChineseNameConverter::getKTVZhuyinAbbr($simplified);// 注音符號
$song->pinyin_abbr=ChineseNameConverter::getKTVPinyinAbbr($simplified);// 拼音首字母
$chars = preg_split('//u', $song->name, -1, PREG_SPLIT_NO_EMPTY);
$firstChar = $chars[0] ?? null;
$song->strokes_abbr=($firstChar && preg_match('/\p{Han}/u', $firstChar)) ? ChineseStrokesConverter::getStrokes($firstChar) : 0;
$song->song_number = mb_strlen($song->name, 'UTF-8');
2025-04-25 09:33:28 +08:00
});
2025-05-14 15:32:54 +08:00
static::deleting(function (Song $song) {
// Detach 關聯資料
$song->artists()->detach();
$song->categories()->detach();
$song->branches()->detach();
$song->users()->detach();
});
2025-04-25 09:33:28 +08:00
}
}