php Laravel 如何将两个查询结果合并为单个对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44535539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:00:07  来源:igfitidea点击:

Laravel how merge two query result into single object

phplaravelobjectlaravel-5backend

提问by PenAndPapers

I'm currently stuck on how to merge two query result into 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'}]

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

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

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

回答by Jakir Hossain

You can use all() function.

您可以使用 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'}]

回答by Hiren Makwana

Try merge()

尝试 merge()

The mergemethod 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 />';
});

回答by Pat

Adding my answer as the above solutions didn't quite work for me, both just added two separate objects to one array: {"Name":"A Name"},{"Surname":"A Surname"}. I had to collect my array and use first.

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

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

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

回答by NinetyHH

Personally I am not a fan on transforming 2 possible big queries in Collections and merge them, seems like a lot of processing in there.

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

I normally use union(), maybe this can help others. Laravel documentation for unions

我通常使用 union(),也许这可以帮助其他人。 工会的 Laravel 文档

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

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