Laravel eloquent 关系没有给我我想要的

Laravel eloquent relationship not giving me what i want

我试图弄清楚 eloquent 并且很难理解它,即使我尝试阅读它。

我有两个 table:fs_festivals 和 fs_bands。

fs_festivals: id, name

fs_bands: id, festival_id, 名字

所以,一个音乐节可以有多个乐队,一个乐队属于一个音乐节。

乐队模型 (Band.php)

class Band extends Eloquent implements UserInterface, RemindableInterface {

use UserTrait, RemindableTrait;

protected $fillable = array(
    'festival_id','name','note','bandak', 'bandakinfo','created_by','updated_by'
);

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'fs_bands';

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = array('password', 'remember_token');

public function festival() {
    return $this->belongsTo('Festival');
}

}

节日模型(Festival.php):

class Festival extends Eloquent implements UserInterface, RemindableInterface {

use UserTrait, RemindableTrait;

protected $fillable = array(
    'name','year','info','slug', 'image','created_by','updated_by'
);

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'fs_festivals';

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = array('password', 'remember_token');

public function bands() {
    return $this->hasMany('Band');
}

}

在我的控制器中:

    public function festivalHome() {
   $bands = Band::all();
    return View::make('fis.festivalhome')->with('bands',$bands);
}

在我看来:

Bands: 
@foreach($bands as $band)
{{ $band->name }}
@endforeach

这列出了 fs_bands table 中的所有波段。我只想列出那些设置了当前节日的 festival_id 的人(比如 festival_id='2')。我该怎么办?

我已经试过了(看看别人是怎么做的),

@foreach($festival->$bands as $band)

但是它给我一个错误

Undefined variable: festival

我做错了什么?我也想知道,我是否应该做其他事情而不是 $bands = Band:all();按 festival_id 列出它们?那将是一个选项,但有些东西告诉我这应该使用 eloquent.

自动完成

控制器:

public function festivalHome($id) {
      //$bands = Band::all();
      $festival = Festival::with('bands')->whereId($id)->first(); //it will load festival with all his bands 
      return View::make('fis.festivalhome')->with('festival',$festival);


      // or you can filter bands
      $bands = Band::whereHas('festival', function($query) use ($id){ 
                     $query->whereId($id);
               })->get(); //there will be only bands which will be on the festival

   }

在您看来:

@foreach($festival->bands as $band)
   {{ $band->name }}
@endforeach

 //or 
 @foreach($bands as $band)
   {{ $band->name }}
 @endforeach