Laravel从数据透视表中仅获取certrain数据 [英] Laravel Getting only certrain data from pivot table
本文介绍了Laravel从数据透视表中仅获取certrain数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Laravel查询得分较高的用户(eventscore表中的行)我想返回ID为3的所有具有该事件分数的用户
I'm using Laravel to query users that have a score ( row in eventscore table ) And i want to return all the users that have scores for the event with an ID of 3
是否只能返回在数据透视表中找到的每个用户的分数(请参见下面的结果)
Is it possible to only return the score of every user, found in the pivot table ( see results below )
这是我正在使用的代码
$persons = Person::whereHas('eventscore', function($q) {
$q->where('id', 3);
})->with('eventscore')->get();
return $persons;
谢谢!
推荐答案
尝试一下:
// Person model
// accessor for easy fetching the score from the pivot model
public function getScoreAttribute()
{
return ($this->pivot && $this->pivot->score)
? $this->pivot->score
: null;
}
// example usage for the event's page (I assume participants is the relation)
$event = Event::with('participants')->find(3);
// somewhere in the view template
@foreach ($event->participants as $participant)
{{ $participant->name }} - score: {{ $participant->score }}
@endforeach
这篇关于Laravel从数据透视表中仅获取certrain数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文