2017-10-20 66 views
0

這裏有兩類:Laravel 5.5,如何禁用自動發現關係到Array/JSON?

class Category extends Model { 

    protected $fillable = [ 
     'title', 'slug' 
    ]; 

    protected $appends = [ 
     'url' 
    ]; 

    public function subcategories() 
    { 
     return $this->hasMany(Subcategory::class); 
    } 

    public function getUrlAttribute() 
    { 
     return route('catalog::category', ['catSlug' => $this->slug]); 
    } 
} 

class Subcategory extends Model { 

    /** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = [ 
     'title', 'slug' 
    ]; 

    protected $appends = [ 
     'url' 
    ]; 

    public function category() 
    { 
     return $this->belongsTo(Category::class); 
    } 

    public function getUrlAttribute() 
    { 
     return route('catalog::subcategory', ['catSlug' => $this->category->slug, 'subcatSlug' => $this->slug]); 
    } 
} 

接下來,讓我們使用的分類指定者()方法:

$category = Category::first(); 
dd($category->toArray()); 

陣列看起來像預期的:ID,標題,蛞蝓,以及附加的URL字段。但是,如果我使用關係的任何呼叫,他們autoappended數組:

$category = Category::first(); 
$category->subcategories; 
dd($category->toArray()); 

現在陣中還含有場「子類別」,每個項目有包含「類別」,並開始無限遞歸。如果使用諸如$ category-> subcategories() - > get()這樣的調用,則不會發生這種情況,但這對我來說不是好的解決方案

回答