delete(); } else { DB::table('song_library_cache')->truncate(); } } $totalInserted = 0; Song::with(['artists', 'categories'])->chunk(500, function ($songs) use (&$totalInserted) { $rows = []; foreach ($songs as $song) { $sortedArtists = $song->artists->sortBy('id')->values(); $artistA = $sortedArtists->get(0); $artistB = $sortedArtists->get(1); $rows[] = [ 'song_id' => $song->id, 'song_name' => $song->name, 'song_simplified' => $song->simplified, 'phonetic_abbr' => $song->phonetic_abbr ?? '', 'pinyin_abbr' => $song->pinyin_abbr ?? '', 'strokes_abbr' => $song->strokes_abbr ?? 0, 'song_number' => $song->song_number ?? 0, 'artistA' => $artistA?->name, 'artistB' => $artistB?->name, 'artistA_simplified' => $artistA?->simplified, 'artistB_simplified' => $artistB?->simplified, 'artistA_category' => $artistA?->category?->value ?? '未定義', 'artistB_category' => $artistB?->category?->value ?? '未定義', 'artist_category' => in_array(\App\Enums\ArtistCategory::Group->value, [ $artistA?->category?->value, $artistB?->category?->value, ]) ? '團' : '未定義', 'song_filename' => $song->filename, 'song_category' => $song->categories->pluck('code')->unique()->sort()->implode(', '), 'language_name' => $song->language_type ?? '未定義', 'add_date' => $song->adddate, 'situation' => $song->situation?->value ?? '未定義', 'vocal' => $song->vocal, 'db_change' => $song->db_change, 'song_counts' => $song->song_counts ?? 0, 'updated_at' => now(), ]; } collect($rows)->chunk(1000)->each(function ($chunk) use (&$totalInserted) { SongLibraryCache::insert($chunk->toArray()); $totalInserted += $chunk->count(); }); }); // 你也可以 log 或通知插入結果 // logger("Exported {$totalInserted} songs to cache."); } }