在一个laravel的项目中,用到了 setCollection 和 getCollection 方法,在官方的文档找不到其用法?
直接上代码:
$result = Category::query()
->where('is_directory', true)
->where('name', 'like', '%' . $search . '%')
->paginate();
$result->setCollection($result->getCollection()->map(function (Category $category) {
return ['id' => $category->id, 'text' => $category->full_name];
}));
查看源码文件 AbstractPaginator.php, 提到
/**
* Get the paginator's underlying collection.
*
* @return \Illuminate\Support\Collection
*/
public function getCollection()
{
return $this->items;
}
/**
* Set the paginator's underlying collection.
*
* @param \Illuminate\Support\Collection $collection
* @return $this
*/
public function setCollection(Collection $collection)
{
$this->items = $collection;
return $this;
}
getCollection() 方法是获取到这个分页里面的结合, setCollection() 就是把分页的数据替换