2014-11-08 105 views
1

我在數據透視表中有一個額外的列,我需要訪問它。Laravel - 訪問數據透視表中的額外列數據

架構:

Schema::create('alert_criteria', function(Blueprint $table) 
{ 
    $table->increments('id'); 
    $table->integer('alert_id')->unsigned()->index(); 
    $table->foreign('alert_id')->references('id')->on('alerts')->onDelete('cascade'); 
    $table->integer('criteria_id')->unsigned()->index(); 
    $table->foreign('criteria_id')->references('id')->on('criterias')->onDelete('cascade'); 
    $table->integer('viewed'); 
    $table->timestamps(); 
}); 

標準模態

public function alerts() 
{ 
    return $this->belongsToMany('Alert')->withPivot('viewed')->withTimestamps(); 
} 

控制器

public function getMatches() 
{ 
    $matches = Criteria::find(Auth::user()->id) 
    ->alerts() 
    ->get(); 
} 

查看:

@foreach($matches as $match) 
    <td>{{$match->viewed}}</td> 
    @endforeach 

視圖不返回一個錯誤,但它只是不顯示任何東西。 「觀看」列僅爲1或0.

非常感謝提前。

回答

3

要訪問其他的數據透視表的列添加到您的關係聲明:

public function alerts(){ 
    return $this->belongsToMany('Alert')->withPivot('viewed'); 
} 

然後,爲了訪問它,你必須使用pivot財產

@foreach($matches as $match) 
    <td>{{$match->pivot->viewed}}</td> 
@endforeach 

Reference

+0

在我的'標準'模型,我現在有'公共功能警報() \t { \t \t返回$ this-> belongsToMany('Alert') - > withPivot('viewed') - > withTimestamps(); '但是它仍然沒有返回值? – Ben 2014-11-08 20:35:28

+0

對不起,我忘了添加如何訪問它。答案已更新。 – lukasgeiter 2014-11-08 20:37:33

+0

謝謝@lukasgeiter,它完美的工作。 – Ben 2014-11-08 20:40:15