【问题标题】:Get all the attributes related to one Model as JSON以 JSON 格式获取与一个模型相关的所有属性
【发布时间】:2014-09-07 09:21:48
【问题描述】:

我有这个模型给作者:

<?php


class Author extends Eloquent {    

  public function albums()
  {
    return $this->belongsToMany('Album')->withPivot('city');
  }

}

专辑的这个模型:

<?php


class Album extends Eloquent {

  public function artist()
  {
    return $this->belongsTo('Artist');
  }

  public function authors()
  {
    return $this->belongsToMany('Author')->withPivot('city');
  }

}

要获得模型,我可以很容易地做到这一点:

$author = Author::where('name','=','Chester Bennington')-&gt;first()-&gt;toJson();

它会返回类似这样的东西(作为 JSON):

{"id":3,"name":"Chester Bennington","created_at":"2014-06-29 16:10:21","updated_at":"2014-06-29 16:10:21"}

请注意它不会返回与其相关的相册。要获得专辑,我必须这样做:$author-&gt;albums-&gt;toJson()

由于我正在做一个 API,它以 JSON 形式返回所有内容,有没有办法在不指定要获取哪些属性的情况下获取模型及其所有属性??

【问题讨论】:

  • 你试过$author = json_encode(Author::with('albums')-&gt;where('name','=','Chester Bennington')-&gt;first());
  • 刚刚回答了我的问题,谢谢。

标签: json laravel laravel-4


【解决方案1】:

如果您需要eager load the relationships,它将包含在您的 JSON 中:

Author::with('albums')->where('name', 'Chester Bennington')->first()->toJson();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-15
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 2015-09-01
    • 2021-09-02
    相关资源
    最近更新 更多