简体   繁体   English

如何使用 Eloquent 从中间表中获取所有关系?

[英]How do I use Eloquent to get all relationships from an intermediate table?

I have many to many relationships, eg:我有很多关系,例如:

// 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');
    }
}

Let's say I have the following category / section relationships with the following slugs:假设我与以下 slug 有以下类别/部分关系:

domestic
    dogs
    cats
    birds
zoo
    cats
    birds
winged
    birds

Is there an Eloquent or easy way to list all of the sections with their category?是否有 Eloquent 或简单的方法来列出所有部分及其类别?

To put this in context, if category and section had a slug, based on my example, I would like to get a list of sections like this:把这个放在上下文中,如果类别和部分有一个 slug,根据我的例子,我想得到一个像这样的部分列表:

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

I have tried to create a Pivot model by extending the Pivot class but can't work it out.我试图通过扩展 Pivot 类来创建一个 Pivot 模型,但无法解决。

Any help greatly appreciated.非常感谢任何帮助。

Something like this could do the trick:像这样的事情可以解决问题:

// 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从eloquent,silex中的中间表中获取数据 - How to get data from intermediate table in eloquent, silex 从 Eloquent model 获取所有关系 - Get all relationships from Eloquent model 如何通过中间表从一个模型到另一个模型使用雄辩 - How To use Eloquent in From One Model to another model through intermediate table 为什么雄辩的模型关系不使用括号,它们如何工作? - Why eloquent model relationships do not use parenthesis and how do they work? 当涉及联合表时,我如何处理 Laravel Eloquent 关系? - How do I approach Laravel Eloquent Relationships when there is a joint table involved? Laravel 5.1 /雄辩:如何使用第三张表从第二张表中进行选择 - Laravel 5.1 / Eloquent: How do I use a 3rd table to select from the second table 如何在不使用 Eloquent 的情况下在 Laravel 中使用多表查询 - How to use Multi table queries in Laravel without using Eloquent Relationships 如何获得雄辩的模型关系以返回结果而不是空数组 - How do I get my eloquent model relationships to return results instead of empty array 如何将数据获取到 Eloquent 中具有许多关系的表 - How to get data to table that has many relationships in Eloquent 我应该如何使用Laravel雄辩的查询和使用关系? - How should I use Laravel Eloquent queries and use relationships?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM