我正在尝试将从Eloquent模型中检索到的一些数据转换为对象,然后也使用Laravel的分页功能。但是,当我将数据强制转换为数组以进行转换时,就不能使用paginate方法了。
$postsPerPage = 10;
$posts = Post::where('published', '=', true)->get();
$posts = Helpers::transform_posts($posts->toArray());
// $posts = Helpers::transform_posts($posts->toArray())->paginate($postsPerPage);
// doesn't work because $posts has been cast to an array
// error: Call to a member function paginate() on a non-object
return View::make('blog.index', ['posts' => $posts]);
类助手:
public static function transform_post(array $post)
{
$publishedDate = CarbonCarbon::createFromTimeStamp(strtotime($post['published_date']))->diffForHumans();
return [
'id' => $post['id'],
'title' => $post['title'],
'slug' => $post['slug'],
'subtitle' => $post['subtitle'],
'body' => $post['body'],
'published' => (bool)$post['published'],
'published_date' => $post['published_date'],
'published_date_for_humans' => $publishedDate
];
}
public static function transform_posts(array $posts)
{
foreach ($posts as &$array) {
$array = Helpers::transform_post($array);
}
return $posts;
}
我怎么能做到这一点,而不强制转换到一个数组,这样我仍然可以在数据上使用分页方法?
编辑:这现在解决了:
$posts = Post::where('published', '=', true)->get()->toArray();
$posts = Helpers::transform_posts($posts);
$posts = Paginator::make($posts, 0 , $postsPerPage);
return View::make('blog.index', ['posts' => $posts]);
试一试:
$posts = Post::where('published', '=', true)->get()->toArray();
$paginator = Paginator::make($posts, $totalItems, $perPage);
您是否尝试过在没有将$posts转换为数组的情况下进行分页?
$posts = Post::where('published', '=', true)->paginate($postsPerPage);