【发布时间】:2014-03-05 21:33:39
【问题描述】:
所以我正在运行带有本地化的表,但我将字符串保存在单独的“主”表中。
假设我对每个实体都有一个表:
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 输出的字段?
编辑:发现https://github.com/laravel/framework/issues/745
所以使用$hidden 我可以隐藏特定字段。整洁。
编辑:使用$appends 和getNameAttribute() 访问器方法,我可以为我的json 创建一个新属性。问题解决了!
【问题讨论】:
-
如果您能发布您的答案并将其标记为已解决会更好吗?你用过这个:laravel.com/docs/5.0/eloquent#accessors-and-mutators?