Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'}]

like image 899
PenAndPapers Avatar asked Jun 14 '17 04:06

PenAndPapers


2 Answers

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'}]
like image 86
Jakir Hossain Avatar answered Sep 23 '22 13:09

Jakir Hossain


Try merge()

The merge method merges the given array or collection with the original collection.

$first = ModelName::where('<fieldName>','<searchText>')
        ->get();
$second = Album::where('<fieldName>','<searchText>')
    ->get();

$finalResult = $first->merge($second);

$finalResult->each(function($record)
{
    echo $record-><fieldName>.'<br />';
});
like image 45
Hiren Makwana Avatar answered Sep 21 '22 13:09

Hiren Makwana