【发布时间】: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 资源。