KTV/app/Models/Artist.php

58 lines
1.7 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 Artist extends Model
{
/** @use HasFactory<\Database\Factories\ArtistFactory> */
2025-05-12 14:13:56 +08:00
use HasFactory, LogsModelActivity;
2025-04-25 09:33:28 +08:00
protected $fillable = [
'category',
2025-04-25 09:33:28 +08:00
'name',
'simplified',
'phonetic_abbr',
'pinyin_abbr',
'strokes_abbr',
2025-05-06 13:04:32 +08:00
'enable',
2025-04-25 09:33:28 +08:00
];
protected function casts(): array
{
return [
'category' => \App\Enums\ArtistCategory::class,
];
}
2025-05-12 14:13:56 +08:00
2025-04-25 09:33:28 +08:00
public function songs() {
return $this->belongsToMany(Song::class);
}
protected static function booted()
{
// 無論是 creating 或 updating都執行這段共用的邏輯
2025-05-14 15:32:54 +08:00
static::saving(function (Artist $artist) {
2025-04-25 09:33:28 +08:00
$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 && preg_match('/\p{Han}/u', $firstChar) ) ? ChineseStrokesConverter::getStrokes($firstChar) : 0;
2025-04-25 09:33:28 +08:00
});
2025-05-14 15:32:54 +08:00
static::deleting(function (Artist $artist) {
// 解除與歌曲的多對多關聯
$artist->songs()->detach();
});
2025-04-25 09:33:28 +08:00
}
}