2017-06-26 221 views
3

我有一個模型: 播放機, 播放, 下載, 軌道Laravel 5.4雄辯查詢

關係:

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

我試圖找到一個查詢,給我對象名單用於追蹤:

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能與雄辯的對象鍵的作品,這將是幾乎我所需要的:

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

groupBy作品有一個字符串鍵,以便在我的問題不會有用。

+0

嗨,我可以看到三個表的結構? –

+0

玩家:[鏈接](http://icecream.me/uploads/5ff1dae239e5424fe4db5ca65451486c.png)播放:[鏈接](http://icecream.me/uploads/276e8e9611c4a31878a2a0e25ae332a6.png)下載:[鏈接](http:/ /icecream.me/uploads/276e8e9611c4a31878a2a0e25ae332a6.png)曲目:[鏈接](http://icecream.me/uploads/a629b99a589fd3a18d2d8024e6170e47.png) – fiter

+0

好的,我發佈了一個答案。 –

回答

1

沒有關於plays()方法和其他方面的更多信息,我能說的最好的是您發佈的代碼將不起作用,因爲$plays是一個集合。嘗試做這種方式(在這種情況下,$plays是一個查詢生成器對象):

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

我嘗試過'groupBy('plays.player_id')'但出現錯誤:SQLSTATE [42000]:語法錯誤或訪問衝突:1055 SELECT列表的表達式#1不在GROUP BY子句中,並且包含非聚集列' muzoperator.plays.id',它在功能上依賴於GROUP BY子句中的列;這與sql_mode = only_full_group_by不兼容(SQL:select * from'plays',其中'plays'.'track_id' = 15和'plays'.'track_id'不爲null,year('created_at')= 2017和month(' created_at')= 5 group by'plays'.'player_id') – fiter

1

昨天我睡着了,所以無法響應更快,但我認爲你可能需要的是這樣的:

// 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'); 

下面的代碼片段只是如何在視圖頁面中調用此數據的示例。 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> 
+0

這看起來相當不錯...但我不能在我的vujs數據表組件上使用它((你可以在我編輯的問題上看到這個組件代碼 – fiter

+0

其實,我不知道vuejs,但也許如果你能解釋組件的目的是什麼,以及你試圖實現的輸出...... –

+0

我期待那種來自laravel的json - [link](http ://icecream.me/uploads/6212abd2f613cfcce817d482debbbe36.png) – fiter