0

我有一个Collection包含根类别和所有后代的。在我的Category模型中,我已经确定可以有许多与该类别相关的帖子。我使用以下代码检索类别及其后代:

$category = Category::findOrFail($categoryID);
$categoryAndDescendants = $category->getDescendantsAndSelf();

$categoryAndDescendants是一个保存模型的Collection对象。Category是否可以一次检索所有帖子?

我基本上想做类似的事情:

$posts = $categoryAndDescendants->posts()->orderBy('timestamp', 'DESC');

这将检索该特定集合中所有类别及其后代的所有帖子。

感谢您的帮助,我为糟糕的措辞道歉。

4

1 回答 1

0

我认为这是不可能的。

但是您可以编写一个自定义集合,并实现此功能。像这样的东西:

<?php 
use Illuminate\Support\Collection;

class CategoryCollection extends Collection
{

    public function posts()
    {
        $posts = new Collection();

        foreach ($this->items as $category) {
            foreach ($category->posts() as $post) {
                $posts->add($post);
            }
        }

        return $posts;
    }
}

然后,您只需将此自定义集合设置为您的 Category 模型。

class Category extends Eloquent
{

    public function newCollection(array $models = array())
    {
        return new CategoryCollection($models);
    }
}
于 2013-09-06T19:40:49.490 回答