【问题标题】:How to return a nested JSON format with given table structure using Laravel如何使用 Laravel 返回具有给定表结构的嵌套 JSON 格式
【发布时间】:2019-12-02 17:53:44
【问题描述】:

如果我有如下表结构,我应该如何使用 Eloquent ORM 返回以下 JSON 格式?

表结构:

authors
    id - integer
    name - string

posts
    id - integer
    author_id - integer
    title - string

images
    id - integer
    post_id - integer
    filename - string

我希望返回的 JSON 格式:

[
  {
    "id": 1,
    "name": "Jeffrey",
    "posts": [
      {
        "id": 1,
        "title": "Hello World",
        "images": [
          {
            "id": 12,
            "filename": "my-image.jpg"
          },
          {
            "id": 13,
            "filename": "your-image.jpg"
          }
        ]
      },
      {
        "id": 5,
        "title": "Lorem Ipsum",
        "images": [
          {
            "id": 20,
            "filename": "his-image.jpg"
          },
          {
            "id": 22,
            "filename": "her-image.jpg"
          }
        ]
      }
    ]
  }
]
  • 表结构:一个作者可能有很多帖子,一个帖子可能有很多图片
  • JSON 格式:图片嵌套在帖子中,帖子嵌套在作者中

已编辑

感谢提醒,我也添加了他们的模特:

<?php  

namespace App;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}
<?php  

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function author()
    {
        return $this->belongsTo('App\Author');
    }

    public function images()
    {
        return $this->hasMany('App\Image');
    }
}
<?php  

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

【问题讨论】:

  • 您是否在 PHP 中编写过任何代码来获得此结果?如果是这样,请向我们展示,因为我们从一开始就工作得更好,并且通常代码会为问题添加大量信息
  • 如果您正在创建 api,请阅读 eloquent 资源。

标签: php json laravel eloquent


【解决方案1】:

如果您将关系 Posts 添加到您的 Author 模型并将关系 Images 添加到您的 Posts 模型,您将能够发出这样的请求,它将为您获取所有数据。

Author::with('posts.images')->get();

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2021-11-06
    • 2019-12-14
    相关资源
    最近更新 更多