【问题标题】:Laravel - Query just one row in a pivot table and return all data within the relationshipLaravel - 仅查询数据透视表中的一行并返回关系中的所有数据
【发布时间】:2014-11-12 19:16:08
【问题描述】:

目前,criteria BelongsToMany alerts 反之亦然。它们通过数据透视表关联:criteria_idalert_id

我正在获取所有 Criteria 以及属于经过身份验证的用户的关联 Alerts,例如:

public function getMatches()
    {
        $matches = Criteria::whereUserId( Auth::id() )
        ->has('alerts')
        ->get();

    }

这会返回所有相关的结果,而现在,如果用户选择了某个结果,我希望能够显示该结果。这是我目前所拥有的:

控制器

public function getMatchDetails($alert_id, $criteria_id)
{

    $matches = Alert::find($alert_id)
    ->has('criterias')
    ->where('criteria_id', $criteria_id)
    ->get();

}

这带来了正确的变量,但是,我收到了一个 MYSQL 错误:

未找到列:1054 'where 子句'中的未知列 'criteria_id'

select * from `alerts` where `alerts`.`deleted_at` is null and 
(select count(*) from `criterias` inner join `alert_criteria` on `criterias`.`id` =
`alert_criteria`.`criteria_id` where `alert_criteria`.`alert_id` = `alerts`.`id`)
>= 1 and `criteria_id` = 7)

任何帮助将不胜感激。

【问题讨论】:

  • 我对“如果用户选择某个结果”的意思感到困惑。第一个查询没有获取关联关系,它只是检查关系是否存在。

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


【解决方案1】:

你可以试试这样的

public function getMatchDetails($alert_id, $criteria_id)
{

    $match = Alert::whereHas('criterias', function ($q) use ($criteria_id) {
        $q->where('criteria_id', $criteria_id);
    })->find($alert_id);

}

它将通过 id 找到警报,并检查它是否与满足这些要求的标准有关系。

【讨论】:

  • 谢谢@lagbox!非常感谢。
【解决方案2】:

我不知道我是否理解这个问题,但我会尝试回答

如果您想将多个变量从视图传递给控制器​​,您可以执行以下操作: 查看

@foreach($matches as $match)
    @foreach($match->alerts as $alert)
        <td>{{$alert->pivot->criteria_id}}</td>
        <td><a href="/users/alert/matches/{{{$alert->id}}}/{{{$var_2}}}">{{$alert->id}}</a></td> 
    @endforeach
@endforeach

控制器

public function getMatchDetails($id, $var_2 = 0)
{
        $myCriteriaIds = Criteria::whereUserId( Auth::id() )
        ->lists('id');

        $match = Alert::find($id)->criterias()
                        ->wherePivot('criteria_id', 'IN', $myCriteriaIds)
                        ->get();
}

路线

Route::post('/users/alert/matches/{id}/{var_2}', array(
    'as' => 'users-alert-matches',
    'uses' => 'XXXController@getMatchDetails'
));

【讨论】:

  • 非常感谢@jibe_84,它已经清理了很多。我仍在为最终查询而苦苦挣扎(请参阅更新后的问题)。
  • 好的,太好了!因此,请尝试通过“->where('criteria.id', $criteria_id)”//criteria_id 将您的控制器中的 where 子句更改为 criteria.id
猜你喜欢
  • 2016-01-29
  • 1970-01-01
  • 2020-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 2020-08-09
  • 2019-02-19
相关资源
最近更新 更多