使用Laravel数据透视表生成干净格式化的json

tif*_*ang 5 json laravel eloquent

所以我正在运行具有本地化的表,但我将字符串保存在单独的"主"表中.

假设我有一个每个实体的表:

Products
  id
  price
  ...
Run Code Online (Sandbox Code Playgroud)

翻译表

Translations
  id
  name
  description
  ...
Run Code Online (Sandbox Code Playgroud)

关系表

product_translation
  product_id
  translation_id
  lang --enum('en', 'es', 'fr',...)
Run Code Online (Sandbox Code Playgroud)

问题:这不是那么漂亮的json

所以我创建了一个BaseModel使用多对多关系的东西:

public function translations()
{
  return $this
  ->belongsToMany('Translation')
  ->where('lang', '=' App::getLocale());
}
Run Code Online (Sandbox Code Playgroud)

所以我可以Product::with('translations')->get()为我的json 做.然而...

我想要的

{
    "name": "Foo",
    "description": "Bar",
    "price": "1000",
    "stock": "10",
}
Run Code Online (Sandbox Code Playgroud)

我得到了什么

{
  "id": "1",
  "price": "1000",
  "stock": "10",
  "translations": [
    {
      "id": "1",
      "name": "Foo",
      "description": "Bar",
      "pivot": {
        "product_id": "1",
        "translation_id": "1"
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的那样,输出的包袱太多了.如何限制我想要生成所需json输出的字段?

编辑:发现https://github.com/laravel/framework/issues/745

所以使用$hidden我能够隐藏特定的字段.整齐.

编辑:使用$appends带有getNameAttribute()存取方法,我能创造一个新的属性,以我的JSON.问题解决了!

San*_*rez 0

您可以使用 Laravel 查询来仅获取您需要的属性。请参阅文档:http://laravel.com/docs/5.0/queries#selects

addind ->select() 只接收您真正需要的内容怎么样?