所以我使用本地化運行表,但我將這些字符串保存在單獨的「主」表中。使用Laravel數據透視表生成乾淨的格式化json
說我對每個實體的表:
Products
id
price
...
轉換表
Translations
id
name
description
...
關係表
product_translation
product_id
translation_id
lang --enum('en', 'es', 'fr',...)
問題:不能這麼漂亮的JSON來與此
所以我創建了一個BaseModel
它採用了多對多的關係:
public function translations()
{
return $this
->belongsToMany('Translation')
->where('lang', '=' App::getLocale());
}
因此,既然我能爲我的JSON做Product::with('translations')->get()
。然而...
我想
{
"name": "Foo",
"description": "Bar",
"price": "1000",
"stock": "10",
}
我該怎麼
{
"id": "1",
"price": "1000",
"stock": "10",
"translations": [
{
"id": "1",
"name": "Foo",
"description": "Bar",
"pivot": {
"product_id": "1",
"translation_id": "1"
}
}
]
}
正如你可以看到有隻是太多的行李與輸出。如何限制我想要生成所需的json輸出的字段?
編輯:因此使用$hidden
,我能夠隱藏特定的領域發現https://github.com/laravel/framework/issues/745
。整齊。
編輯:使用$appends
與getNameAttribute()
訪問器方法我能夠創建一個新的屬性到我的JSON。問題解決了!
將是很好,如果你可以發佈你的答案和標記以此作爲解決?你用過這個:http://laravel.com/docs/5.0/eloquent#accessors-and-mutators? – wiesson