首页 > 解决方案 > 如何使用 Eloquent 从中间表中获取所有关系?

问题描述

我有很多关系,例如:

// Category Model
class Category extends Model
{
    public function sections()
    {
        return $this->belongsToMany('App\Section');
    }
}

// Section Model
class Section extends Model
{
    public function categories()
    {
        return $this->belongsToMany('App\Category');
    }
}

假设我与以下 slug 有以下类别/部分关系:

domestic
    dogs
    cats
    birds
zoo
    cats
    birds
winged
    birds

是否有一种雄辩的或简单的方法来列出所有部分及其类别?

为了把它放在上下文中,如果 category 和 section 有一个 slug,基于我的例子,我想得到一个这样的部分列表:

domestic/dogs
domestic/cats
domestic/birds
zoo/cats
zoo/birds
winged/birds

我试图通过扩展 Pivot 类来创建一个 Pivot 模型,但无法解决。

非常感谢任何帮助。

标签: phplaraveleloquent

解决方案


像这样的东西可以解决问题:

// Retrieve all categories
$categories = Category::with('sections')->all();

// Define result array
$result = [];

foreach ($categories as $category) {
    foreach ($category->sections as $section) {
        $result[] = $category->slug . '/' . $section->slug;
    }
}

// Result now holds the contents you are looking for

推荐阅读