【发布时间】:2015-03-13 00:33:12
【问题描述】:
我试图弄清楚它的雄辩并很难理解它,即使我试图阅读它。
我有两张桌子:fs_festivals 和 fs_bands。
fs_festivals:id、名字
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 表中的所有波段。我只想列出那些设置了我正在处理的当前节日的节日 ID 的人(比如节日 ID='2')。我该怎么办?
我试过这个(看看别人做了什么),
@foreach($festival->$bands as $band)
但它给了我一个错误
未定义变量:节日
我做错了什么?我也想知道,我应该做点别的而不是 $bands = Band:all();按festival_id 列出它们?这将是一个选项,但有些东西告诉我这应该用 eloquent 自动完成。
【问题讨论】:
标签: php laravel eloquent relationship