0

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

我的观点

@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');
        
    }

在此处输入图像描述

有人能告诉我我做错了什么吗?

4

1 回答 1

2

默认情况下,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
于 2015-01-20T13:45:43.207 回答