[英]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.