Laravel:从相关表中获取/显示数据

时间:2014-08-27 09:41:59

标签: laravel laravel-4

我有两个相关的表格如下:

出版商

| id | name     |
|----|----------|
| 1  | EA Games |
| 2  | Nintendo |

游戏

| id | publisher_id | title       |
|----|--------------|-------------|
| 1  | 1            | FIFA 2014   |
| 2  | 2            | Super Mario |
| 3  | 1            | The Sims    |

我的索引页面是这样构建的:

public function index(){
    $games = Game::all();
    return View::make('/games/index', compact('games'));
}

当然,我的Blade模板是这样的:

<table class="table table-striped">
    <thead>
        <tr>
            <th>Title</th>
            <th>Publisher</th>
            <th>Complete</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @foreach($games as $game)
        <tr>
            <td>{{ $game->title }}</td>
            <td>{{ $game->publisher_id }}</td>
            <td>{{ $game->complete }}</td>
            <td>
                <a href="{{ action('GamesController@edit', $game->id) }}" class="btn btn-default">Edit</a>
                <a href="{{ action('GamesController@delete', $game->id )}}" class="btn btn-danger">Delete</a>
            </td>
        </tr>
        @endforeach
    </tbody>
</table>

在出版商&#39;我希望显示发布商名称(取自发布者和数据库表格),而不是发布商&#39;编号

拜托,我怎么能实现这个目标?

提前致谢

1 个答案:

答案 0 :(得分:1)

您需要通过将此方法添加到游戏模型来设置模型关系:

public function publisher()
{
    return $this->belongsTo('Publisher');
}

然后您可以在视图中使用$ game-&gt; publisher-&gt;名称。

相关问题