[英]appending like data when Joining two tables when two columns of one table refer to a third one in Laravel
[英]laravel two columns that represent one table
好的,我正在構建足球經理網絡應用。 我有一個團隊表:
------------------
| id | name |
------------------
| 1 | Barcelona |
------------------
| 2 | Madrid |
------------------
我也有一個season_games表,這里是精簡版:
------------------------------------------
| id | season_id | away_team | home_team |
------------------------------------------
| 1 | 1 | 1 | 2 |
------------------------------------------
| 2 | 1 | 2 | 1 |
-------------------------------------------
這用於檢索球隊即將發布的游戲,例如html:
<table>
<thead>
<tr>
<th>Season Name</th>
<th>Home Team</th>
<th>Away Team</th>
<th>Score</th>
<th>Date</th>
</tr>
</thead>
<tbody>
@foreach($all_games as $game)
<tr>
<td>
{{ $game->seasons->name }}
</td>
<td>
{{ $game->home_team }}
</td>
<td>
{{ $game->away_team }}
</td>
<td>
{{ $game->home_score . " x " . $game->away_score}}
</td>
<td>
{{ $game->game_date }}
</td>
</tr>
@endforeach
</tbody>
</table>
好吧,我想做的就是做到,away_team和home_team都與teams表相關。 在我看來,我不需要運行getNameFromId函數,因為顯然有數百種游戲意味着數百種sql查詢。 什么是解決此問題的有效方法?
聯接將是很棒的,因為您不必進行瑣碎的查詢。 假設您的模型設置如下:團隊游戲我會使用原始語句來做到這一點:
Game::join('teams AS t1', 't1.id', '=', 'matches.away_team')
->join('teams AS t2', 't2.id', '=', 'matches.home_team')
->select('matches.id', 't1.name', 't2.name')
->get();
減少服務器端查詢的一種方法是將比賽中顯示的所有ID返回給客戶端,並將Teams表中的那些行返回給客戶端並在客戶端進行解碼。 請給我反饋。 這是我第一次寫回應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.