首页 > 解决方案 > 我如何修复 Illuminate\Database\Eloquent\Collection 类的错误对象无法转换为 int

问题描述

我的页面应该显示来自不同表格的总和。当我尝试用代码求和时:

        $games = Game::where('winner_id', $user->id)->get();
        $games_low = GameLow::where('winner_id', $user->id)->get();
        $wins = $games + $games_low->count();
        $wins = $wins;
        $totalBank = $games->sum('price');

我收到错误Object of class Illuminate\Database\Eloquent\Collection could not be converted to int。我该如何解决这个问题?

标签: laravel

解决方案


问题 - 集合

+使用对象 ( $games) 和数字 ( )导致错误$games_low->count()

$games     = Game::where('winner_id', $user->id)->get(); // Collection
$games_low = GameLow::where('winner_id', $user->id)->get(); // Collection

$games_low->count() // int

解决方案

用于和count_GameGameLow

$games     = Game::where('winner_id', $user->id)->count();
$games_low = GameLow::where('winner_id', $user->id)->count();
$wins      = $games + $games_low;

dd($wins);

更新

我怎样才能正确显示变量的总和?在我有一个变量之前,我使用$totalBank = $games->sum('price');了我现在需要的方式来显示总和$games$games_low我不知道

$games     = Game::where('winner_id', $user->id);
$games_low = GameLow::where('winner_id', $user->id);
$wins      = $games->count() + $games_low->count();
$totalBank = $games->sum('price');

推荐阅读