这是两个类:
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上使用toArray()方法:
$category = Category::first();
dd($category->toArray());
数组看起来像预期的:id,title,slug和追加的url字段。但是,如果我使用任何对关系的调用,他们会自动挂起到数组:
$category = Category::first();
$category->subcategories;
dd($category->toArray());
现在数组也包含字段“子类别”,每个项目都包含“类别”,并启动无休止的递归。如果使用$ category-> subcategories() - > get()之类的调用,则不会发生这种情况,但这对我来说不是一个好方法
答案 0 :(得分:0)
您可以使用$hidden
属性来定义模型序列化后应隐藏哪些字段。
https://laravel.com/docs/5.5/eloquent-serialization#hiding-attributes-from-json