Laravel 的集合写法

file

刻意练习,每日精进
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

追踪源码可知在Illuminate/Pagination/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 方法返回值是一个集合对象,然后集合对象就可以调用集合中的map方法对值进行操作.然后再次调用setCollection方法返回的是当前对象,也就是Illuminate\Pagination\LengthAwarePaginator这个分页对象,就是Laravel-admin需要的数据格式.

以下是我在tinker中测试的结果:


总结就是先转换成集合对象,然后调用集合的map方法对数据进行操作,然后再重新转换回来分页对象.

5年前 评论
讨论数量: 4

追踪源码可知在Illuminate/Pagination/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 方法返回值是一个集合对象,然后集合对象就可以调用集合中的map方法对值进行操作.然后再次调用setCollection方法返回的是当前对象,也就是Illuminate\Pagination\LengthAwarePaginator这个分页对象,就是Laravel-admin需要的数据格式.

以下是我在tinker中测试的结果:


总结就是先转换成集合对象,然后调用集合的map方法对数据进行操作,然后再重新转换回来分页对象.

5年前 评论

@Flourishing 分析的很透彻,可以出师了

5年前 评论

@Flourishing 怎么定位到这个文件的Illuminate/Pagination/AbstractPaginator.php 我只能用全局搜索定位这个方法。

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!