Laravel - 无法访问数据透视表数据

时间:2015-01-10 21:31:16

标签: sqlite laravel laravel-4 eloquent pivot-table

我很难让Eloquent玩得很开心;我的查询似乎总有问题。无论如何,我有一个Item类,通过Length表与r_item_length有多对多的关系。在数据透视表中,还有一个value字段。这是Item模型:

模型/分贝/ Item.php:

class Item extends Eloquent implements UserInterface, RemindableInterface {
    ...

    protected $fillable = ['item_singular', 'item_plural'];

    public function length() 
        {
            return $this->belongsToMany('Length', 'r_item_length')->withPivot('value');
        }
}

我正在尝试从枢轴表中获取给定value的{​​{1}}。目前,我正试图在我的视图中访问它:

视图/分贝/ show.blade.php

Item

<body> <table> @foreach ($items as $item) <tr class="record"> <td>{{ $item->id }}</td> <td>{{ $item->item_singular }}</td> <td>{{ $item->item_plural }}</td> </tr> <tr> <td>{{ var_dump($item->length->first()->pivot->value) }}</td> </tr> @endforeach </table> </body> 正在给我一个错误:“试图获取非对象的属性”。搜索几个小时后,看起来这个语法应该是可以接受的,$item->length->first()->pivot,但是我无法让它工作。我也是这样尝试的,$item->length->first()->pivot->value,但当然,它不起作用,因为我已经定义了两者之间的多对多关系。

这表明我的模型设置方式有问题吗?我只是错误地查询它吗?谢谢你的帮助。

以下是$item->length->pivot->value中第一项的输出。

var_dump($item->length->first())

1 个答案:

答案 0 :(得分:3)

问题恰好是某些Item没有分配Length。因此$item->length->first()为空,因此访问pivot会引发错误。解决方案非常简单。只需包裹一个if就可以了。你应该没问题。

<tr>
    @if($length = $item->length->first())
        <td>{{ $length->pivot->value }}</td>
    @endif
</tr>