【问题标题】:RESTful API - Array to Collection Laravel 5RESTful API - 数组到集合 Laravel 5
【发布时间】:2015-07-07 05:33:53
【问题描述】:

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

我试过了

\Illuminate\Support\Collection::make(DB::select(...));

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

是否可以将 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());

这仍然告诉我:

FatalErrorException in QueryHelper.php line 36:
Call to a member function skip() on array

干杯

【问题讨论】:

    标签: php arrays laravel-5


    【解决方案1】:

    我会尝试:

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

    如果查询结果是一个数组,则集合中会填满您的结果。请参阅该集合的官方文档。 Laravel5 Collections

    【讨论】:

    • 感谢您的评论。我使用 Collection::make() 管理了该部分,不幸的是我仍然无法对集合运行 skip() 和 take()。
    • 我不确定你所说的 skip() 和 take() 是什么意思。 Collection 类没有这样的方法。 Collection你能发布你想对收藏做什么吗?
    • 是的,抱歉,我对 Collection 类的理解有限。我想要做的是使用 skip 和 take 方法手动构建分页标题。不幸的是,这些方法似乎只在 Query\Builder 类中可用。我得另寻他法。不过还是谢谢。
    • forpage() 方法非常适合分页(Taylor 像往常一样考虑了大多数用例 :)
    【解决方案2】:

    对于在 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))
            );
    

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

    【讨论】:

      猜你喜欢
      • 2016-05-19
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 2016-02-28
      • 2015-05-03
      • 2015-06-13
      • 1970-01-01
      • 2018-09-22
      相关资源
      最近更新 更多