【问题标题】:Laravel - returning only certain columns within a has functionLaravel - 仅返回具有函数中的某些列
【发布时间】:2015-02-09 19:15:22
【问题描述】:

目前,下面的函数可以正常工作,但是,->has('alerts') 返回整个 alerts 数组,包括所有关系数据。我只想从该关系中返回某些列。

public function getMatches()
        {
            $matches = Criteria::select('id')
            ->has('alerts')
            ->with(['alerts.location' => function($w){
                $w->select('id');
            }])
            ->with('alerts.user.companies')
            ->where('user_id', Auth::id())
            ->get();

            return Response::json(array(
                'matches' => $matches,
                'status' => '200'
                )
            );

        }

我想返回的列可以在刀片格式中访问(注意也使用的枢轴)

@foreach($matches as $match)
    @foreach($match->alerts as $alert)  
        {{$alert->pivot->criteria_id}}
        {{$alert->pivot->alert_id}}
        {{$alert->price_value}}
        {{$alert->location->type}}
        {{$alert->category}}
        {{$alert->description}}
        {{$alert->category}}
        {{$alert->user->companies->first()->logo->url('thumb')}}
        {{$alert->pivot->viewed}} 
    @endforeach
@endforeach

我尝试了以下方法:

public function getMatches()
    {
        $matches = Criteria::select('id')
        ->has(['alerts' => function ($q){
            $q->select('id', 'pivot.criteria_id');
        }])
        ->with(['alerts.location' => function($w){
            $w->select('id');
        }])
        ->with('alerts.user.companies')
        ->where('user_id', Auth::id())
        ->get();

    }

但我收到以下错误:

strpos() expects parameter 1 to be string, array given

has()函数中添加以下函数时出现错误:

->has(['alerts' => function ($q){
    $q->select('id', 'pivot.criteria_id');
}])

对于如何从“警报”表中选择所述字段以及相应关系的任何帮助,我将不胜感激。

【问题讨论】:

  • strpos() 是否在 Laravel 的 ->has() 函数中被调用?或者你在什么地方叫它?我只是问,因为我没有看到你在任何地方打电话。
  • 只要将function 添加到has() 中,就会发生错误,所以我非常有信心这就是发生错误的地方。

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


【解决方案1】:

在你的代码中你有这样的东西:

->has(['alerts' => function ($q){
    //...
}])

应该是这样的:

->whereHas('alerts', function ($q){
    //...
})

【讨论】:

    【解决方案2】:

    您不想为此使用haswhereHashas 函数仅用于根据关系过滤结果。要仅选择某些列,请使用 with()

    $matches = Criteria::select('id')
        ->has('alerts')
        ->with(['alerts' => function($q){
            $q->select('id', 'pivot.criteria_id');
        }, 'alerts.location' => function($w){
            $w->select('id');
        }])
        ->with('alerts.user.companies')
        ->where('user_id', Auth::id())
        ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 2018-02-20
      • 1970-01-01
      • 2022-01-04
      • 2017-03-19
      • 2018-03-09
      相关资源
      最近更新 更多