拉拉维尔雄辩的关系没有给我我想要的


Laravel eloquent relationship not giving me what i want

我试图弄清楚雄辩并很难理解它,甚至我试图阅读它。

我有两个表:fs_festivals和fs_bands。

fs_festivals:ID、姓名

fs_bands:身份证、festival_id、姓名

所以,一个音乐节

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

乐队

模型(乐队.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');
}

}

节日

模式(节日.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表中的所有波段。我只想列出那些设置了当前节日festival_id的人(比如festival_id='2')。我应该怎么做?

我试过这个(看看别人做了什么),

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

但它给了我一个错误

未定义的变量:节日

我做错了什么?我也想知道,我应该做点别的事情而不是$bands = Band:all();按festival_id列出它们?这将是一种选择,但有些事情告诉我,这应该通过雄辩自动完成。

控制器:

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