php – Laravel 5.4 Eloquent查询

我有一个模特:
播放器,
玩,
下载,
跟踪

关系:

Player has many Play and Download
Play and Download belongs to Player
Track has many Play and Download

我正在尝试查找一个查询,该查询为我提供了一个Track的对象列表:

Track 
--Player
----Plays
----Downloads
--Player
----Plays
----Downloads
--Player
----Plays
----Downloads

我在vuejs数据表组件中使用它:

<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>

如果groupBy可以使用Eloquent对象键,那么它几乎就是我需要的:

$plays = $track->plays()->whereYear('created_at', $year )->whereMonth( 'created_at', $month )->with('player')->get();
$players = $plays->groupBy('player');

但是groupBy使用字符串键,因此在我的问题中没用.

最佳答案
如果没有关于plays()方法和其他方法的更多信息,我可以说最好的是你发布的代码不起作用,因为$plays是一个集合.尝试这样做(在这种情况下,$plays是一个Query Builder对象):

$plays = $track->plays()->whereYear('created_at', $year )->whereMonth( 'created_at', $month )->with('player');
$players = $plays->groupBy('player')->get();

转载注明原文:php – Laravel 5.4 Eloquent查询 - 代码日志