简体   繁体   中英

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:

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?

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM