无法访问分页联合查询结果的项目

时间:2016-12-11 11:27:59

标签: php laravel pagination laravel-5.3

我想分页联盟查询结果。我写了这个:

    use Illuminate\Support\Facades\Input;
    use Illuminate\Pagination\Paginator;

    $page = Input::get('page', 1);
    $paginate = 10;

    $members = DB::table("members")
                ->select("id", "first_name", "last_name", "email", "created_at")
                ->where("site_id", $id);

    $users = DB::table("users")
                ->select("id", "first_name", "last_name", "email", "created_at")
                ->where("site_id", $id)
                ->union($members)
                ->get()->toArray()

    $slice = array_slice($users, $paginate * ($page - 1), $paginate);
    $data = new Paginator($slice, $paginate);

    return View::make('main.pages.search',compact('data','searchTerm'));

现在我想在search刀片模板中访问结果。假设我写了这个:

<div class="container">
    @foreach ($data as $user)
        {{ $user->first_name }}
    @endforeach
</div>

{{ $data->links() }}

但我收到了这个错误:

Trying to get property of non-object (View: D:\wamp\www\aids\resources\views\main\pages\search.blade.php

无法识别$username属性

有什么问题?

更新
而来自上面的return $data来自这个:

{
    "per_page": 2,
    "current_page": 1,
    "next_page_url": null,
    "prev_page_url": null,
    "from": 1,
    "to": 2,
    "data": [
        {
            "id": 6,
            "first_name": "ali",
            "last_name": "hassani",
            "created_at": "2012-04-16 22:11:46",
            "email": "ali@gmail.com",
        },
        {
            "id": 7,
            "first_name": "hossein",
            "last_name": "rezaei",
            "created_at": "2012-04-16 22:11:46",
            "email": "reza@gmail.com",
        },
    ]
}

我尝试$data->data访问结果但发生了同样的错误。

更新2:

我发现当我添加{{dd($user)}}时这样:

<div class="container">
    @foreach ($data as $user)
        {{dd($user)}}
        {{ $user->first_name }}
    @endforeach
</div>

返回array包含结果而不是object

2 个答案:

答案 0 :(得分:1)

在您的控制器中,您在查询结果上调用函数toArray,该函数将集合转换为纯PHP Javascript。如果集合的值是Eloquent模型,模型也将转换为数组。

因此,您的array视图应为:

foreach

答案 1 :(得分:0)

根据@iCode指南,我发现我应该使用slice代替array_slice方法。事实上,使用array_slice的部分代码更改为:

$slice = $workshops->slice($paginate * ($page - 1), $paginate);