2015-01-14 67 views
-1

即時通訊試圖弄清楚口才,難以理解,即使是生活也試圖讀懂它。Laravel雄辯的關係不給我我想要的

我有兩個表: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表中的所有頻段。我只想列出那些正在設置當前藝術節即將開展的festival_id(比如festival_id ='2')的人。我應該怎麼做呢?

伊夫嘗試這種(看別人怎麼做),

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

但它給我的

未定義變量的錯誤:節日

我在做什麼錯?另外我想知道,我應該做一些其他的事情而不是$ band = Band:all();按festival_id列出它們?這將是一個選擇,但有些事情告訴我,這應該通過雄辯自動完成。

回答

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 
+0

這給了我:未定義的屬性:照亮\數據庫\雄辯\生成器:: $樂隊(查看:在/ var/WWW/html/fis/app/views/fis/festivalhome.blade.php) –

+0

忘記first()方法:)修復 – xAoc

+0

工作正常。我使用:$ festival = Festival :: with('bands') - > whereId($ festivalid) - > first();然後@foreach($ festival-> bands爲$ band) {{$ band-> name}} @endforeach 非常感謝Dmytro! –