58 lines
1.7 KiB
PHP
58 lines
1.7 KiB
PHP
<?php
|
||
|
||
namespace App\Models;
|
||
|
||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||
use Illuminate\Database\Eloquent\Model;
|
||
use App\Helpers\ChineseNameConverter;
|
||
use App\Helpers\ChineseStrokesConverter;
|
||
use App\Traits\LogsModelActivity;
|
||
|
||
class Artist extends Model
|
||
{
|
||
/** @use HasFactory<\Database\Factories\ArtistFactory> */
|
||
use HasFactory, LogsModelActivity;
|
||
|
||
protected $fillable = [
|
||
'category',
|
||
'name',
|
||
'simplified',
|
||
'phonetic_abbr',
|
||
'pinyin_abbr',
|
||
'strokes_abbr',
|
||
'enable',
|
||
];
|
||
|
||
protected function casts(): array
|
||
{
|
||
return [
|
||
'category' => \App\Enums\ArtistCategory::class,
|
||
];
|
||
}
|
||
|
||
public function songs() {
|
||
return $this->belongsToMany(Song::class);
|
||
}
|
||
|
||
protected static function booted()
|
||
{
|
||
// 無論是 creating 或 updating,都執行這段共用的邏輯
|
||
static::saving(function (Artist $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 && preg_match('/\p{Han}/u', $firstChar) ) ? ChineseStrokesConverter::getStrokes($firstChar) : 0;
|
||
});
|
||
|
||
static::deleting(function (Artist $artist) {
|
||
// 解除與歌曲的多對多關聯
|
||
$artist->songs()->detach();
|
||
});
|
||
}
|
||
|
||
}
|