目前,对于用户,我可以正确返回所有matches
。
public function getMatches()
{
$matches = Criteria::whereUserId( Auth::id() )
->has('alerts')
->with('alerts.location', 'alerts.user.companies')
->get();
$this->layout->content = View::make('users.alert.matches',
array('matches' => $matches));
}
关系:
一个Criteria
属于许多Alerts
,一个Alert
属于许多Criterias
。
问题:
如果用户希望查看有关某个匹配项的更多信息,我想从数据库中get
该结果。在我看来,我可以访问第一个forloop
内的criteria_id
,以及第二个forloop
内的alert_id。
@foreach($matches as $match)
{{$match->id}}
@foreach($match->alerts as $alert)
{{$alert->id}}
@endforeach
@endforeach
但是,如何使用这些变量来仅选择用户要查看更多信息的一个数据透视表匹配项?
如果用户要选择某个 {{$alert->id}},我如何找到与该alert_id相关的criteria_id,然后查询数据库以仅返回该行信息,包括来自criteria
表和alert
表,以及上面显示的 with->
语句。
非常感谢您的帮助。
我认为您可以将数据透视表中的数据包含在您的热切加载中,如下所示:
public function getMatches()
{
$matches = Criteria::whereUserId( Auth::id() )
->has('alerts')
->with('alerts.location', 'alerts.user.companies')
->withPivot('foo', 'bar'); //pivot table columns you need from pivot table criteria_alert
->get();
$this->layout->content = View::make('users.alert.matches',
array('matches' => $matches));
}
并像这样访问它:
@foreach($matches as $match)
{{$match->id}}
@foreach($match->alerts as $alert)
{{$match->pivot->foo}} // pivot table data
{{$alert->id}}
@endforeach
@endforeach
查看 laravel 文档以获取更多详细信息。
此外,这可能有助于简化代码:
$matches = Auth::user()->with('criterias', 'criterias.alert')->get();
使用您的条件来提醒关系,如下所示:
return $this->belongsToMany('Alert')->withPivot('foo', 'bar');
希望这有帮助。