Laravel 分页方法不适用于地图集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45903926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel paginate method not working with map collection?
提问by Manchester
$items = Item::with('product')->paginate(10);
$items = $items->map(function($product){
$product->name = "Test";
return $product;
});
return response()->json(['items' => $items]);
In my view blade on console paginate objects not showed?
在我的控制台分页对象上的视图刀片未显示?
回答by jaysingkar
As, given in Laravel docs, Map()
method creates a new collection. To modify the values in the current collection, use transform()
method.
正如Laravel 文档中给出的那样,Map()
方法创建了一个新集合。要修改当前集合中的值,请使用transform()
方法。
$items->getCollection()->transform(function ($product) {
$product->name = "Test";
return $product;
});
Also, since, paginator's items is a collection. You can use foreach
directly on $items
此外,因为分页器的项目是一个集合。您可以foreach
直接使用$items
foreach ($items as $item)
{
$item->name = "Test";
}
回答by Bara' ayyash
You should save the data in a collection, work on them, inject them back, something like this:
您应该将数据保存在一个集合中,处理它们,将它们注入回去,如下所示:
$page = Input::get('page', 1);
$data = Item::with('product')->getByPage($page, 10);
$tempItems = $data->items;
$tempItems = $tempItems->map(function($product){
$product->name = "Test";
return $product;
});
$objects = Paginator::make($tempItems, $data->totalItems, 10);