0

我正在尝试在 Laravel 中缓存一个对象。

$categories = Cache::remember('categories', 10, function () {
    return Category::with('forums')
    ->select('id', 'name')
    ->orderBy('order')
    ->get();
});

问题是我在论坛模型中有一些附加值。

protected $appends = ['number_of_topics', 'number_of_replies', 'last_post'];

public function getNumberOfTopicsAttribute() {

    return Topic::where('forum_id', '=', $this->id)
        ->count();

}

public function getNumberOfRepliesAttribute() {

    return Reply::whereExists(function ($query) {
        $query->select(DB::raw(1))
            ->from('topics')
            ->whereColumn('topics.id', '=', 'replies.topic_id')
            ->where('topics.forum_id', '=', $this->id);
    })->count();

}

public function getLastPostAttribute() {

    $lastPost = new LastPost($this->id);

    if ($lastPost->topic_id == null) {

        return null;

    }

    return $lastPost;

}

所有附加的值都不会被缓存。如何使它们与 $categories 一起缓存?

4

0 回答 0