【问题标题】:Generating clean formatted json with Laravel pivot tables使用 Laravel 数据透视表生成干净格式的 json
【发布时间】: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 我可以隐藏特定字段。整洁。

编辑:使用$appendsgetNameAttribute() 访问器方法,我可以为我的json 创建一个新属性。问题解决了!

【问题讨论】:

标签: json laravel eloquent


【解决方案1】:

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

addind ->select() 只接收你真正需要的东西。

【讨论】:

    【解决方案2】:

    这是应该添加到类 Product 中的代码(正如问题本身所回答的那样):

    class Product {
    
        protected $hidden = ['id', 'translations'];
    
        protected $appends = ['name', 'description'];
    
        public function getNameAttribute()
        {
            return $this->translations->name;
        }
    
        public function getDescriptionAttribute()
        {
            return $this->translations->description;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      • 2016-08-11
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多