【问题标题】:Laravel - Select just one row from pivot table and return dataLaravel - 从数据透视表中只选择一行并返回数据
【发布时间】:2014-11-10 21:33:25
【问题描述】:

目前,对于一个用户,我可以正确返回所有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));
}

关系:

一个CriteriabelongsToMany Alerts 和一个AlertbelongsToMany 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}},我如何找到哪个criteria_id 与该alert_id 相关,然后查询数据库以返回刚刚那一行信息,两者都来自@ 987654332@ 表和alert 表,以及上面显示的with-> 语句。

非常感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

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

    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');
    

    希望这会有所帮助。

    【讨论】:

    • 嗨@Kazma,谢谢你的回复。我稍微修改了您的代码,但它完全按照我的需要工作。我现在如何仅使用一个结果的条件 ID 和警报 ID 查询数据库?
    • 如果我正确理解了您的问题,您希望获取带有criteria_id 和alert_id 的标准数据和警报数据。为此,您可以使用具有查找功能的 Eloquent 模型,例如 Criteria::find($criteria_id) 和 Alert::find($alert_id)
    • 现在您已经向我展示了如何访问 $alert_id 及其关联的 $criteria_id,我现在只想获取这些行。它们由数据透视表链接,因此我想在 alert_criteria 上选择 * where alert_id = $alert_id and criteria_id = $criteria_id。
    • 您可以使用枢轴函数 $criteria = Criteria::find($criteria_id); foreach ($criteria->alert as $alert) { echo $alert->pivot->foo; }
    猜你喜欢
    • 1970-01-01
    • 2013-11-15
    • 2021-08-21
    • 1970-01-01
    • 2015-02-14
    • 2018-07-06
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    相关资源
    最近更新 更多