Laravel - 从数据透视表中只选择一行并返回数据

时间:2014-11-10 21:33:26

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

目前,对于用户,我可以正确返回所有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所属的商家AlertsAlert belongsToMany Criterias

问题:

如果用户希望查看有关某个匹配项的更多信息,我希望get只是来自数据库的结果。在我看来,我可以访问第一个criteria_id内的forloop和第二个forloop内的alert_id。

@foreach($matches as $match)
    {{$match->id}}
        @foreach($match->alerts as $alert)
            {{$alert->id}}
        @endforeach
@endforeach

但是,如何使用这些变量只选择一个用户想要查看更多信息的数据透视表匹配?

如果用户要选择某个{{$ alert-> id}},如何查找哪个criteria_id与该alert_id相关,然后查询数据库以返回该行的信息,两者均来自criteria表和alert表,以及上面显示的with->语句。

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我认为您可以将数据透视表中的数据包含在您的预先加载中,如下所示:

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 documentation了解详情。

此外,这可能有助于您简化代码:

$matches = Auth::user()->with('criterias', 'criterias.alert')->get();

根据您的标准来提醒这样的关系:

return $this->belongsToMany('Alert')->withPivot('foo', 'bar');

希望这有帮助。

相关问题