У меня есть метод в моей модели . модель, которая извлекает список всех игр, зарегистрированных в таблице на одной базе данных, итерации через каждую найденную игру и получение данных из другой базы данных, и, наконец, захватывает URL-адрес случайного изображения из базы данных и добавляет его в объект статистики. Еще не запутались?Laravel :: Объединить два объекта запросов БД
не следует путать больше нет, вот метод:
public static function getStats($player, $cache = 30) {
// Return a collection of all games registered from the website database
$games = Game::get(['game']);
foreach($games as $game) {
// For each iteration, return the statistics from the games database for that game
// Grab game meta information from the website database, $game->game is the game name.
$list = Game::where('game', $game->game)->remember($cache)->first();
// From the game database, retrieve the statistics
$stats[$game->game] = DB::connection('game')->table($list->stats_table)
->select(DB::raw($list->statistics))
->where('Username', $player)
->remember($cache)
->first();
// Grab a random map image from the game database
$stats[$game->game]['map'] = DB::connection('game')->table('Maps')
->select('Image')
->orderBy(DB::raw('RAND()'))
->remember($cache)
->first();
}
// Finally, return the statistics from the game paired with a random map image from the game
return $stats;
}
Я хотел бы добавить запрос карту на $ статы так что все в одном месте, в настоящее время этот метод терпит неудачу из-за: Невозможно использовать объект type stdClass as array
Без карт при циклизации по $ stats это массив статистики игр с ключом в качестве названия игры.
Если вы все еще смущены (я не буду вас обвинять), оставьте комментарий, и я объясню больше.
EDIT:
Вот моя попытка с помощью ->merge()
:
public static function getStats($player, $cache = 30) {
// Return a collection of all games registered from the website database
$games = Game::get(['game']);
foreach($games as $game) {
// For each iteration, return the statistics from the games database for that game
// Grab game meta information from the website database
$list = Game::where('game', $game->game)->remember($cache)->first();
// From the game database, retrieve the statistics
$stats[$game->game] = DB::connection('game')->table($list->stats_table)
->select(DB::raw($list->statistics))
->where('Username', $player)
->remember($cache)
->first();
// Grab a random map image from the game database
$map = DB::connection('game')->table('Maps')
->select('Image')
->orderBy(DB::raw('RAND()'))
->remember($cache)
->first();
$stats[$game->game] = $stats[$game->game]->merge($map);
}
// Finally, return the statistics from the game paired with a random map image from the game
return $stats;
}
Какие результаты в Вызов неопределенной метод StdClass :: слияния() работает Laravel 4.2.
Так что, если вы должны были изменить этот пример, чтобы соответствовать моим, результат был бы '$ данных [$ игра-> игра] -> Merge ($ карта)' с ' $ map' переименовывается из $ data [$ game-> game] ['map'] – davidxd33
См. править с помощью попытки. – davidxd33
им не удается понять, что вы пытаетесь получить. это merge() применимо только к красноречивым коллекциям. – thegeekajay