doushansu9012 2015-04-28 11:27
浏览 71
已采纳

RESTful API - 收集Laravel 5的数组

I'm having issues with an array returned from DB::select(). I'm heavily using skip and take on Collections of eloquent models in my API. Unfortunately, DB::select returns an array, which obviously doesn't work with skip and take's. How would one convert arrays to a collection that can utilise these methods?

I've tried

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

Which doesn't quite work as I expected, as it wraps the entire array in a Collection, not the individual results.

Is it possible to convert the return from a DB::select to a 'proper' Collection that can use skip and take methods?

Update

I've also tried:

$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());

Which still tells me:

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

Cheers

  • 写回答

2条回答 默认 最新

  • dongtuo5262 2015-04-29 09:52
    关注

    For anyone else that's having this sort of problem in Laravel, I figured out a work around with the following solution:

            $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))
            );
    

    Basically, I wasn't aware that you could run the queries almost incrementally, which enabled me to generate pagination chunks before limiting the data returned.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集