laravel表示一个表的两列


laravel two columns that represent one table

好吧,我正在构建一个足球经理web应用程序。我有一个团队表:

------------------
| id  | name      |                 
------------------
| 1   | Barcelona |
------------------
| 2   | Madrid    |
------------------

我还有一个季节名称表,这里是一个精简版:

------------------------------------------
| 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_tam都与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表中的这些行返回到客户端并在那里进行解码。请给我反馈。这是我第一次写回复。