Skip to content
Advertisement

Laravel how merge two query results into a single object

I’m currently stuck on how to merge two query results into a single object . Below is my code.

EDITED

Model methods

public static function getTeamStats($competitionId, $teamId) {
    return TeamCompetitionStatistics::where('competitionId', $competitionId)
        ->where('teamid', $teamId)
        ->where('periodNumber', 0)
        ->get();
}

public static function getTeamPosition($competitionId, $teamId){
    return self::where('latest', 1)
        ->where('competitionId',$competitionId)
        ->where('competitorId', $teamId)
        ->get(['position', 'streak'])
        ->map(function($item, $key){
            $item->position = $item->position . date("S", mktime(0, 0, 0, 0, $item->position, 0));
            if(strpos($item->streak, '-') !== FALSE) {
                $item->streak = str_replace('-', 'L', $item->streak);
            }
            else {
                $item->streak = 'W'.$item->streak;
            }
            return $item;
        });
}

Getting values in controller

$teamStanding = Ladder::getTeamPosition($request->competitionId, $request->id);
$teamStatistics = TeamCompetitionStatistics::getTeamStats($request->competitionId, $request->id);

$result = $teamStatistics->merge($teamStanding);

Returned result: [{'teamstanding': 'data'}, {'teamstatictics': 'data'}]

Expected output: [{'teamstanding': 'data', 'teamstatictics': 'data'}]

Advertisement

Answer

You can use all() function.

$teamStanding = Ladder::getTeamPosition($request->competitionId, $request->id)->get();

$teamStatistics = TeamCompetitionStatistics::getTeamStats($request->competitionId, $request->id)->get();

$merged = $teamStatistics->merge($teamStanding);

$result = $merged->all();

// return [{'teamstanding': 'data', 'teamstatictics': 'data'}]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement