Laravel 如何将两个查询结果合并到一个对象中

Laravel how merge two query results into a single object

我目前正在研究如何将两个查询结果合并到一个对象中。下面是我的代码。

已编辑

模型方法

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;
        });
}

在控制器中获取值

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

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

返回结果:[{'teamstanding': 'data'}, {'teamstatictics': 'data'}]

预期输出:[{'teamstanding': 'data', 'teamstatictics': 'data'}]

您可以使用 all() 函数。

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

尝试merge()

merge 方法将给定数组或集合与原始集合合并。

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

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

$finalResult->each(function($record)
{
    echo $record-><fieldName>.'<br />';
});

添加我的答案,因为上述解决方案对我来说不太适用,两者都只是将两个单独的对象添加到一个数组中:{"Name":"A Name"},{"Surname":"A Surname"}。我必须收集我的阵列并先使用。

https://laravel.com/docs/5.4/collections#method-merge

$first  = $modelone->where('Id', '1')->first(['Name']);
$second = $modeltwo->where('Thing', '1')->first(['Surname']);

    $collection = collect($first);
    $merged     = $collection->merge($second);
    $result[]   = $merged->all();
    return $result;
//output: [{"Name":"A Name","Surname":"A Surname"}]

就我个人而言,我不喜欢在 Collections 中转换 2 个可能的大查询并将它们合并,似乎其中有很多处理。

我通常使用union(),也许这对其他人有帮助。 Laravel documentation for unions

$first = DB::table('users')
        ->whereNull('first_name');

$users = DB::table('users')
        ->whereNull('last_name')
        ->union($first)
        ->get();