我试图找出雄辩并且很难理解它,甚至我试图阅读它。
我有两个表:fs_festivals和fs_bands。
fs_festivals:id,name
fs_bands:id,festival_id,name
所以,一个节日可以有很多乐队,一个乐队属于一个节日。
乐队模型(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表中的所有波段。我只想列出那些使用当前节日的festival_id设置的人(比如festival_id =' 2')。我该怎么办呢?
我试过这个(看看别人做了什么),
@foreach($festival->$bands as $band)
但它给了我一个错误
未定义的变量:节日
我做错了什么?我也想知道,我应该做别的事而不是$ bands = Band:all();用festival_id列出它们?这将是一个选择,但有些东西告诉我,这应该用雄辩的方式自动完成。
答案 0 :(得分:1)
控制器:
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