How to show count of relationship from a belongs to many through relationship?

models:
song
playlist
artist

song n n artist
playlist n n song

a playlist has many artist through their songs. idk how to set that relationship in the playlist model. so im doing it like this:
file: playlistresource - inside table columns:
Tables\Columns\TextColumn::make('artists_count')
    ->getStateUsing(function (Playlist $record): int {
        return $record->songs->map(function (Song $song) {
            return $song->artists()->pluck('artists.id');
        })->unique()->flatten()->count();
    })
    ->sortable()
,
is there any potential improvements in the query?

if i knew how to set it, id do it like this. im trying to find out how to do it.
Tables\Columns\TextColumn::make('artists_count')
    ->counts('artists')
    ->sortable()
,
Was this page helpful?