Laravel:如何在集合中返回数组?

时间:2017-01-31 16:58:04

标签: laravel-5.3

我要求所有的运动员数据来自这样的api电话,一切都很好。

MyController.php

public function get($year, $position_id)
{
    $collection = collect(
        $athletes = Athlete::where('athletes.graduation_year', $year)
            ->join('athlete_position', 'athlete_position.athlete_id', '=', 'athletes.id')
            ->where('athlete_position.position_id', '=', $position_id)
            ->join('evaluations', 'evaluations.athlete_id', 'athletes.id')
            ->whereNotNull('evaluations.comments')
            ->where('evaluations.status', 'published')
            ->orderBy('rank', 'asc')
            ->orderBy('rating', 'asc')
            ->orderBy('last_name', 'asc')
            ->get()
    )->groupBy('rating');

    return response()->json(['data' => $collection], 200);
}

我现在想将此商品表添加到此商家中:

...
->join('evaluations', 'evaluations.athlete_id', 'athletes.craft_id')
->whereNotNull('evaluations.comments')
->where('evaluations.status', 'published')
->join('offers', 'offers.athlete_id', 'athletes.craft_id')
...

哪个有效,但现在我得到重复的运动员;每个报价一个。例如,如果一名运动员有三项优惠,我会让同一名运动员三次回来 - 每次提供一次。

我想要的是该系列中的一系列优惠。看起来像这样:

$athlete {
    ...
    'evaluation': '<p>My evaluation...</p>',
    'offers': [
        {'school': '<p>Clemson</p>','committed': 1},
        {'school': '<p>Alabama</p>', 'committed': 0} 
    ]
    ...
 }

这样我每位运动员只能获得一条记录,但每位运动员都可以获得很多优惠。

我的模特看起来像这样:

Athlete.php

public function offers()
{
    return $this->hasMany('App\Offer');
}

Offer.php

public function athletes()
{
    return $this->belongsToMany('App\Athlete');
}

所有数据都会在我的整个应用程序中正确返回 - 只是API调用才是我挣扎的地方。

感谢您的任何建议!

修改

以下是我现在的选择:

$collection = collect(
        $athletes = DB::table('athletes')->select('craft_id', 'first_name', 'last_name', 'email', 'high_school_state', 'graduation_year', 'rank', 'rating', 'evaluations.comments', 'offers.school')
            ->where('athletes.graduation_year', $year)
            ->join('athlete_position', 'athlete_position.athlete_id', '=', 'athletes.craft_id')
            ->where('athlete_position.position_id', '=', $position_id)
            ->join('evaluations', 'evaluations.athlete_id', 'athletes.craft_id')
            ->whereNotNull('evaluations.comments')
            ->where('evaluations.status', 'published')
            ->join('offers', 'offers.athlete_id', 'athletes.craft_id')
            ->orderBy('rank', 'asc')
            ->orderBy('rating', 'asc')
            ->orderBy('last_name', 'asc')
            ->get()
    )->groupBy('rating');

它返回数据,如果我有多个要约,而不是将要约作为数组获得,我会得到两个完整的记录。

"data": {
    ...
  {
    "first_name": "Tyler",
    "last_name": "Durden",
    "offers":  "Clemson"
  },
   {
    "first_name": "Tyler",
    "last_name": "Durden",
    "offers":  "Alabama"
  },

我试图获得:

"data": {
...
  {
    "first_name": "Tyler",
    "last_name": "Durden",
    "offers":  [
        "school": "Clemson"
        "school": "Alabama"
    ]
  },

1 个答案:

答案 0 :(得分:0)

使用这种复杂的查询是最好的方法

v-if

这将使您免于重复

documentation