Laravel雄辩的设置数组键

时间:2014-06-05 21:32:26

标签: laravel laravel-4 eloquent

我想创建一个数组,其中键等于返回的 ID 。 但是当我执行这段代码时,我只获得时间戳,存在和递增值。 我无法做toArray(),因为$arr已经是一个数组,所以不知道为什么这是不可能的..

    $projects = Project::with(array('todos', 'contacts', 'categories'))->get();

    foreach ($projects as $project) {
        $open = Todo::status($project->id, 1)->get()->count();
        $progress = Todo::status($project->id, 2)->get()->count();
        $completed = Todo::status($project->id, 3)->get()->count();

        $project->status = [
            'open' => $open,
            'progress' => $progress,
            'completed' => $completed
        ];

        $arr[$project->id] = $project;
        return $arr;
    }

1 个答案:

答案 0 :(得分:0)

也许你可以尝试laravel方式:

$projects = Project::with(array('todos', 'contacts', 'categories'))->get();

$projects->each(function($project){

        $open = Todo::status($project->id, 1)->get()->count();
        $progress = Todo::status($project->id, 2)->get()->count();
        $completed = Todo::status($project->id, 3)->get()->count();

        $project->status = [
            'open' => $open,
            'progress' => $progress,
            'completed' => $completed
        ];

});

return $projects->toArray();

该查询返回一个照明集合对象,您可以利用可用的集合方法而不是自己连接。 http://laravel.com/docs/eloquent#collections