PHP / Eloquent - 遍历集合并设置不在范围内的变量

PHP / Eloquent - Iterate through collection and set variable not in scope

我是 Eloquent 的新手,我花了数小时进行搜索,但找不到解决问题的确切方法。

我有以下型号:

use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Support\Collection;

class Answer extends Eloquent
{
    protected $table = 'tbl_answers';

    protected $fillable = [
       'method',
       'thoughts',
       'location'
    ];

    public function getMethodsStats()
    {
        $methods = Answer::selectRaw('*, count(*) AS method_count')- >groupBy('method');
    return $methods;
    }
}

在我的控制器中,我尝试遍历结果以仅将结果回显到屏幕上。 这有效:

$methods = $app->answer->getMethodsStats();

$methods->each(function($method, $key)
{
    echo " --- Method: " . $method->method . " - " . $method->method_count;
});

输出符合预期:

-- Method: fold - 3 --- Method: crumple - 2

为了方便起见,我想用这些值填充一个数组。一旦完成,这个数组应该可以在 'each' 函数之外访问。

代码:

$methods = $app->answer->getMethodsStats();
$stats = new array();

$methods->each(function($method, $key) use ($stats)
{

    $stats[$method->method] = $method->method_count;
});

echo json_encode($stats);

这不符合我的预期。我只是得到一个空数组。

输出:

[]

我知道我遗漏了一些基本的东西,但 'what' 那是我不知道的。

首先尝试使用 ->toSql()

打印您的 mysql 查询

喜欢

    echo $methods = Answer::selectRaw('*, count(*) AS method_count')- >groupBy('method')->toSql();

die(); 
and check if you are getting the correct query to execute.

然后尝试 改变

$methods = Answer::selectRaw('*, count(*) AS method_count')- >groupBy('method');
    return $methods;

 $methods = Answer::select(DB::Raw('*'), DB::Raw('count(*) AS method_count)')->groupBy('method');
    return $methods;

默认情况下,PHP 按值传递函数参数。您正在将 $stats 的副本 传递给您的函数。您需要改为通过引用传递它,以便函数可以修改它。通过在变量前附加一个 & 来执行此操作,如下所示:

$methods->each(function($method, $key) use (&$stats) { ... }); 
 echo json_encode($stats);

值得一看: