Laravel:从相关表中获取/显示数据 [英] Laravel: get/show data from related tables
本文介绍了Laravel:从相关表中获取/显示数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个相关的表格,如下所示:
I have two related tables like this:
发布者
| id | name |
|----|----------|
| 1 | EA Games |
| 2 | Nintendo |
游戏
| id | publisher_id | title |
|----|--------------|-------------|
| 1 | 1 | FIFA 2014 |
| 2 | 2 | Super Mario |
| 3 | 1 | The Sims |
我的索引页面的构建如下:
My index page is built like this:
public function index(){
$games = Game::all();
return View::make('/games/index', compact('games'));
}
当然,我的Blade模板是这样的:
And of course my Blade template is like this:
<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>
在发布者的单元格中,我想显示发布者名称(取自发布者"数据库表),而不是发布者的ID
In the Publishers' cells I'd like to display the publisher name (taken from the 'publishers' DB table), not the publishers' IDs
请,我该如何实现?
预先感谢
推荐答案
您需要通过将以下方法添加到游戏模型中来建立模型关系:
You need to setup your model relationship by adding this method to your Game model:
public function publisher()
{
return $this->belongsTo('Publisher');
}
然后,您可以在视图中使用$ game-> publisher-> name.
Then you can use $game->publisher->name in your view.
这篇关于Laravel:从相关表中获取/显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文