RESTful API - 收集Laravel 5的数组

fan*_*tly 7 php arrays laravel-5

我遇到了从返回的数组的问题DB::select().我大量使用skiptakeCollections我的API雄辩的车型.不幸的是,DB :: select返回一个数组,这显然不适用于skip和take.如何将数组转换为可以使用这些方法的集合?

我试过了

\Illuminate\Support\Collection::make(DB::select(...));
Run Code Online (Sandbox Code Playgroud)

这并不像我预期的那样工作,因为它将整个数组包装在Collection中,而不是单独的结果.

是否有可能将返回从a转换为DB::select可以使用的"正确"集合skiptake方法?

更新

我也尝试过:

$query = \Illuminate\Support\Collection::make(DB::table('survey_responses')->join('people', 'people.id',
        '=', 'survey_responses.recipient_id')->select('survey_responses.id', 'survey_responses.response',
        'survey_responses.score', 'people.name', 'people.email')->get());
Run Code Online (Sandbox Code Playgroud)

还告诉我:

FatalErrorException in QueryHelper.php line 36:
Call to a member function skip() on array
Run Code Online (Sandbox Code Playgroud)

干杯

小智 13

我会尝试:

$queryResult = DB::table('...')->get();

$collection = collect($queryResult);
Run Code Online (Sandbox Code Playgroud)

如果查询结果是数组,则会使用结果填充该集合.请参阅该集合的官方文档.Laravel5系列


fan*_*tly 1

对于在 Laravel 中遇到此类问题的其他人,我找到了使用以下解决方案的解决方案:

        $query = DB::table('survey_responses')->join('people', 'people.id', '=', 'survey_responses.recipient_id')
            ->select('survey_responses.id', 'survey_responses.response', 'survey_responses.score', 'people.name', 'people.email');
            if(isset($tags)){
                foreach($tags as $tag){
                    $query->orWhere('survey_responses.response', 'like', '%'.$tag.'%');
                }
            };

        // We apply the pagination headers on the complete result set - before any limiting
        $headers = \HeaderHelper::generatePaginationHeader($page, $query, 'response', $limit, $tags);
        // Now limit and create 'pages' based on passed params
        $query->offset(
            (isset($page) ? $page - 1 * (isset($limit) ? $limit : env('RESULTS_PER_PAGE', 30)) : 1)
        )
        ->take(
            (isset($limit) ? $limit : env('RESULTS_PER_PAGE', 30))
        );
Run Code Online (Sandbox Code Playgroud)

基本上,我不知道您可以几乎增量地运行查询,这使我能够在限制返回的数据之前生成分页块。