在laravel中 setCollection 和getCollection具體是怎麼用的?

在一個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() 就是把分頁的數據替換

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章