我目前仍然坚持如何将两个查询结果合并到单个对象下面是我的代码。
EDITED
模型方法
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'}]
答案 0 :(得分:11)
您可以使用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'}]
答案 1 :(得分:3)
尝试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 />';
});
答案 2 :(得分:1)
添加我的答案,因为上述解决方案对我而言并不奏效,它们都只是将两个单独的对象添加到一个数组中:{"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"}]
答案 3 :(得分:1)
我个人不喜欢在Collections中转换两个可能的大查询并合并它们,似乎在那里很处理。
我通常使用union(),也许这可以帮助其他人。 Laravel documentation for unions
$first = DB::table('users')
->whereNull('first_name');
$users = DB::table('users')
->whereNull('last_name')
->union($first)
->get();