[英]Laravel appends only one attribute from relationship
我正在嘗試向我的 Laravel 7 API model 添加一個額外的字段:
class Layer extends Model {
protected $fillable = ['name', 'filename', 'status', 'category_id'];
protected $appends = ['category_name'];
public function getCategoryNameAttribute()
{
return $this->category->name;
}
public function category()
{
return $this->belongsTo('App\LayerCategory', 'category_id');
}
}
我的 Controller:
.....
public function index()
{
return Layer::orderBy('name', 'asc')->paginate();
}
.....
我期待以下回應:
{
"id": 1,
"category_id": 1,
"name": "My Layer",
"filename": "file_name.zip",
"status": true,
"category_name": "My category name"
}
但我收到:
{
"id": 1,
"category_id": 1,
"name": "My Layer",
"filename": "file_name.zip",
"status": true,
"category_name": "My category name",
"category": [
"id": 1,
"name": "My category name",
"status": true
]
}
如何只返回類別名稱? PS:我也嘗試過使用資源。
由於您急於加載Category
關系以獲取category_name
,因此您需要添加邏輯以從 JSON 響應中隱藏category
。 這可以使用序列化的隱藏屬性來完成:
protected $hidden = ['category'];
您可以閱讀https://laravel.com/docs/7.x/eloquent-serialization#hiding-attributes-from-json了解更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.