KTV/app/Models/Artist.php

52 lines
1.5 KiB
PHP
Raw 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-04-25 09:33:28 +08:00
class Artist extends Model
{
/** @use HasFactory<\Database\Factories\ArtistFactory> */
use HasFactory;
protected $fillable = [
'category',
2025-04-25 09:33:28 +08:00
'name',
'simplified',
'phonetic_abbr',
'pinyin_abbr',
'strokes_abbr',
2025-04-25 09:33:28 +08:00
];
protected function casts(): array
{
return [
'category' => \App\Enums\ArtistCategory::class,
];
}
2025-04-25 09:33:28 +08:00
public function songs() {
return $this->belongsToMany(Song::class);
}
protected static function booted()
{
// 無論是 creating 或 updating都執行這段共用的邏輯
static::saving(function ($artist) {
$simplified=ChineseNameConverter::convertToSimplified($artist->name);// 繁體轉簡體
$artist->simplified = $simplified;
$artist->phonetic_abbr = ChineseNameConverter::getKTVZhuyinAbbr($simplified);// 注音符號
$artist->pinyin_abbr=ChineseNameConverter::getKTVPinyinAbbr($simplified);// 拼音首字母
$chars = preg_split('//u', $artist->name, -1, PREG_SPLIT_NO_EMPTY);
$firstChar = $chars[0] ?? null;
$artist->strokes_abbr=$firstChar ? ChineseStrokesConverter::getStrokes($firstChar) : null;
2025-04-25 09:33:28 +08:00
});
}
}