N
N
Nurlan2017-04-16 22:04:34
Laravel
Nurlan, 2017-04-16 22:04:34

How to pull models associated with a soft-deleted model?

I didn’t find anything similar in the documentation, but reading the forums I understand that there are a lot of implicit moments.
There is a Song model, which is associated with the Playlist model, and she is with the Artist, but this is no longer important.
I can do Playlist::find(1)->songs and get the songs associated with that playlist, but I got to the stage of deleting the playlist and there was a problem. I soft-deleted the playlist, but the songs do not need to be deleted, which means they remain linked to the playlist that was deleted.
Question:
Is there any way to pull all songs associated with deleted playlists using eloquent and not sql?
Semantically, something like this Playlist::onlyTrashed()->songs
Thanks.

So far the only solution

$songs=Song::join('playlists', 'songs.playlist_id','=','playlists.id')
        ->where('playlists.deleted_at','!=','null')
        ->orderBy('songs.playlist_id','asc')
        ->orderBy('songs.position','asc')
        ->get();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tesla, 2017-04-17
@daager

What's the problem? You get a list of deleted playlists, then iterate through the linked songs.

$playlists = Playlist::onlyTrashed()->with('songs')->get();
foreach ($playlists as $playlist) {
  foreach ($playlist->songs as $song) {
    //
  }
}

If you only want to get a list of songs, remember that EloquentQueryBuilder::get() returns a Collection.
pluck() and sortBy() will help you.
Alternatively, you can get a list of id of deleted playlists, and then select songs from this list:
$playlists = Playlist::onlyTrashed()->get()->pluck('id');
$songs = Song::whereIn('playlist_id', $playlists)->orderBy(...)->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question