【问题标题】:Eloquent to combine data from 2 x tables?雄辩地结合来自 2 x 表的数据?
【发布时间】:2015-08-09 20:05:19
【问题描述】:

表结构:

games

id | name

awards

id | award name | game_id (fk)

关系

一个游戏可以有很多奖项。 一个奖项有一个游戏。

class Games extends Model
{
    public $timestamps = false;

    public function awards()
    {
        return $this->hasMany('award');
    }
}

我需要从我的数据库中取出所有游戏。我这样做是:

Game::all();

然后我需要从我的数据库中取出所有游戏,但包括来自奖励表的数据。

我想要一个可以循环输出游戏的数组,如果游戏有奖励 - 也输出它。

什么是正确的雄辩陈述?

【问题讨论】:

  • 你与Games/Game不一致。解决这个问题! Games::with('awards')->get()呢?
  • 你在使用命名空间吗?

标签: laravel laravel-4 eloquent laravel-5


【解决方案1】:

Laravel 的关系在这种事情上非常出色。到目前为止,您所拥有的一切都在正确的道路上。

// Controller
public function index()
{
    $games = Game::all();

    return view('games.index', compact('games'));
}

// View
@foreach($games as $game)

    {{ $game->name }}

    @if(count($game->awards) > 0)
        // Game has some awards, lets loop through them

        @foreach($game->awards as $award)
            {{ $award->name }}
        @endforeach        

    @endif

@endforeach

使用您在Game 模型中设置的关系,您可以立即访问其他表中的相关数据。现在每次调用 $game->awards 时,它都会查询数据库,但是使用 Laravel 的 Eager Loading,您可以同时提取所有这些信息,而不是按需提取。

// Controller
public function index()
{
    $games = Game::with('awards')->get();

    return view('games.index', compact('games'));
}

并且通过在视图中执行完全相同的操作,您不再需要在每次想要获得游戏奖励时都运行新查询,因为它们已经从数据库中获取。更多关于急切加载这里http://laravel.com/docs/5.0/eloquent#eager-loading

【讨论】:

  • 很好的答案!只是一个简单的问题 - compact 有什么作用?
  • compact 是一个数组构建器,它使用表单输入中的键名作为新数组的值和键。如今,它是一种在 PHP 中构建数组的更短且更符合语法的方式;)
猜你喜欢
  • 2019-05-05
  • 1970-01-01
  • 2020-11-03
  • 1970-01-01
  • 2020-08-04
  • 2013-05-07
  • 2014-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多