Laravel Collection Filter不会根据需要返回数组

时间:2018-01-15 14:11:42

标签: php arrays laravel rest collections

我正在构建REST API,我需要根据EventScores表中未包含的某个EVENT返回TEAMS。 我得到的问题是过滤。如果'team'被'filter'修改,则该方法返回如下内容:

{
"1": {
    "id": 6,
    "name": "sunt",
    "ath1": "Prof. Jarvis Rutherford",
    "ath2": "Joey Gutmann",
    "box": "ut",
    "category_id": 1,
    "totalScore": 6,
    "created_at": "2018-01-11 18:22:13",
    "updated_at": "2018-01-11 19:47:21"
}}

否则,它返回一个ARRAY,这是我需要进入orden在前端制作的东西。以下是我需要的样本:

[
{
    "id": 5,
    "name": "eaque",
    "ath1": "Prof. Trever Grady",
    "ath2": "Angel Walsh",
    "box": "voluptatem",
    "category_id": 1,
    "totalScore": 15,
    "created_at": "2018-01-11 18:22:13",
    "updated_at": "2018-01-11 19:47:21"
}]

这是方法:

public function eventTeams($category_id, $event_id)
{   
    $teams = Team::where('category_id', $category_id)->get();
    $eventScores = EventScores::where('event_id','=', $event_id)->get();
    $teams = $teams->filter(function($team) use($eventScores)
    {     
        if($eventScores->contains('team_id', $team->id)){
            return false;
        }else {
            return true;
        }

    });
    return response($teams, 200);
}

我试过这个:$teamsArr = $teams->toArray()并返回$ teamsArr但它没有用。

2 个答案:

答案 0 :(得分:0)

当你说“它不起作用”时,你的意思是什么?你收到错误吗?

你也可以这样做:

public function eventTeams($categoryId, $eventId)
{   
    $teams = Team::where('category_id', $categoryId)->get();

    $eventScoreTeamIds = EventScores::where('event_id', $eventId)
            ->get() // this will return a collection
            ->pluck('team_id') // get only the team_id
            ->all(); // get results as array

    $teams = $teams->filter(function($team) use($eventScoreTeamIds) {
        return in_array($team->id, $eventScoreTeamIds);     
    });

    return response($teams, 200);
}

答案 1 :(得分:0)

尝试查询数据抛出关系,如下所示:

class Team extends Model
{
    public function eventScores()
    {
        return $this->hasMany('App\EventScores');
    }
}

class EventScores extends Model
{
    public function team()
    {
        return $this->belongsTo('App\Team');
    }
}

class TestController extends Controller
{
    public function index()
    {
        $eventId = 1;
        $categoryId = 1;
        $teams = Team::whereHas('eventScores', function ($query) use ($eventId) {
            $query->where('event_id', $eventId);
        })->where('category_id', $categoryId)
            ->get();
        return response()->json($teams);
    }
}

或者只使用foreach代替过滤器:

$result = [];
foreach ($teams as $team) {
    if ($team->category_id == $categoryId) {
        $result[] = $team;
    }
}
return response()->json($result);