Reputation: 773
I have a models: Player, Play, Download, Track
Relations:
Player has many Play and Download
Play and Download belongs to Player
Track has many Play and Download
I'm trying to find a query that gives me list of objects for a Track:
Track
--Player
----Plays
----Downloads
--Player
----Plays
----Downloads
--Player
----Plays
----Downloads
I use it in vuejs data-table component:
<data-tables
:data='data.players'
>
<el-table-column
prop="place_title">
</el-table-column>
<el-table-column
prop="plays.length">
</el-table-column>
<el-table-column
prop="downloads.length">
</el-table-column>
</data-tables>
If groupBy
could works with an Eloquent object keys, it would be almost what I need:
$plays = $track->plays()->whereYear('created_at', $year )->whereMonth( 'created_at', $month )->with('player')->get();
$players = $plays->groupBy('player');
But groupBy
works with a string keys so that's doesn't useful in my problem.
Upvotes: 4
Views: 490
Reputation: 467
I fell asleep yesterday, so couldn't respond sooner, but I think you might need something like this:
// Assumes you're already fetching the track e.g $track = Track::find($id);
$plays = $track->plays()->with('player')->get();
$plays = $plays->groupBy('player_id');
$downloads = $track->downloads()->with('player')->get();
$downloads = $downloads->groupBy('player_id');
The code snippet below is just an example of how you would call this data in a view page. Screenshot.
<h4>Track {{ $track->id }} Plays</h4>
<ul>
@foreach ($plays as $play)
<li>Player id:{{ $play[0]->player->id }} has played {{ count($play) }} times</li>
@endforeach
</ul>
<b>Total plays: {{ count($track->plays) }}</b>
<h4>Track {{ $track->id }} Downloads</h4>
<ul>
@foreach ($downloads as $download)
<li>Player id:{{ $download[0]->player->id }} has downloaded {{ count($download) }} times</li>
@endforeach
</ul>
<b>Total downloads: {{ count($track->downloads) }}</b>
Upvotes: 1
Reputation: 895
Without more information about the plays()
method and others, the best I can say is the code you posted wouldn't work because $plays
is a Collection. Try doing it this way (in this case, $plays
is a Query Builder object):
$plays = $track->plays()->whereYear('created_at', $year )->whereMonth( 'created_at', $month )->with('player');
$players = $plays->groupBy('player')->get();
Upvotes: 1