繁体   English   中英

Laravel:如何获取特定记录的数据

[英]Laravel: how to get pivot data for a specific record

从文档中我看到->pivot->像这样使用

@foreach($program->attendees as $attendee)
        {{$attendee->pivot->paid;}}
@endforeach

我想像这样找到一个特定$attendee数据透视表...

$program->attendees->find($attendee)->pivot->paid;

但我得到错误: 试图获取非对象的属性

我不知道这是什么问题,因为@foreach版本有效。 如果我跑步
{{$program->attendees->find($attendee)}}

我懂了

{"id":"1","created_at":"2015-03-02 21:35:30","updated_at":"2015-03-02 21:35:30","first_name":"Chris","last_name":"Griffin","birthday":"2010-10-08","media_release":"1","food_allergies":"peanuts","special_care":"","user_id":"2","pivot":{"scheduled_program_id":"1","attendee_id":"1","paid":"0"}} 0 

看起来像是枢轴数据...

请在以下行中查看您的find方法:

$program->attendees->find($attendee)->pivot->paid;

它需要id值来查询模型,然后获取数据透视表。 您是否尝试使用$attendee->id值?

$program->attendees->find($attendee->id)->pivot->paid;

问题在于您是在循环内进行操作,并非每个程序实际上都有一个具有该ID的参与者。

这应该解决它:

@foreach($programs as $program)
    @if($a = $program->attendees->find($attendee))
        {{ $a->pivot->paid }}
    @endif
@endforeach

顺便说一句,我注意到输出末尾的0 那可能是第二个没有这个ID的参与者的程序。

定义关系时,还应使用withPivot()方法,例如:

public function attendees(){
    return $this->belongsToMany('Attendee')->withPivot('paid', 'other_pivot_column');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM