[英]How do I use Eloquent to get all relationships from an intermediate table?
我有很多關系,例如:
// 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
是否有 Eloquent 或簡單的方法來列出所有部分及其類別?
把這個放在上下文中,如果類別和部分有一個 slug,根據我的例子,我想得到一個像這樣的部分列表:
domestic/dogs
domestic/cats
domestic/birds
zoo/cats
zoo/birds
winged/birds
我試圖通過擴展 Pivot 類來創建一個 Pivot 模型,但無法解決。
非常感謝任何幫助。
像這樣的事情可以解決問題:
// 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.