如何从数据透视表中查询数据并使用刀片显示它?

时间:2015-01-20 13:42:19

标签: laravel laravel-4 eloquent laravel-blade

我正在尝试从我的数据透视表中查询数据并将其显示在我的视图

我的观点

@foreach ($catalog_downloads as $catalog_download)
<td>

    <?php $frequencies = $catalog_download->export_frequencies()->get(); ?> 

    {{{ $frequencies }}}

</td>
@endforeach

当我{{{ $frequencies }}}时,我得到了这个:

[{"id":1,"name":"Semi Annual","created_at":"2015-01-14 15:44:59","updated_at":"2015-01-14 15:44:59","pivot":{"catalog_download_id":104,"export_frequency_id":1}},{"id":2,"name":"Quaterly","created_at":"2015-01-14 15:45:06","updated_at":"2015-01-14 15:45:06","pivot":{"catalog_download_id":104,"export_frequency_id":2}},{"id":3,"name":"Monthly","created_at":"2015-01-14 15:45:13","updated_at":"2015-01-14 15:45:13","pivot":{"catalog_download_id":104,"export_frequency_id":3}}]

但我不希望如此。我只想要名称 所以我做了这个{{{ $frequencies->name or '' }}},现在什么都没有出现。 :(

更多详情

以下是我如何定义我的关系。

public function export_frequencies(){ 
        return $this->belongsToMany('ExportFrequency','export_frequency_catalog_download','catalog_download_id','export_frequency_id');

    }

enter image description here

有人可以告诉我,我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

默认情况下,Laravel仅从数据透视表中选择两个外键。要更改,请在您的关系定义中添加withPivot

public function export_frequencies(){
    return $this->belongsToMany('Frequency')->withPivot('name');
});

然后您可以通过pivot对象访问它:

@foreach($frequencies as $frequency)
    {{ $frequency->pivot->name }}
@endforeach

修改

我想我的问题标题让我感到困惑。如果您只是想显示来自ExportFrequency的数据,则不需要withPivot,您只需执行此操作:

@foreach($frequencies as $frequency)
    {{ $frequency->name }}
@endforeach