Laravel - 访问数据透视表中的额外列数据

问题描述:

我在数据透视表中有一个额外的列,我需要访问它。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.

非常感谢提前。

要访问其他的数据透视表的列添加到您的关系声明:

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