Php 从具有Laravel中API的一对一关系的表中获取数据

Php 从具有Laravel中API的一对一关系的表中获取数据,php,laravel,api,laravel-5,Php,Laravel,Api,Laravel 5,我正在做我的第一个Laravel项目,我想为android应用程序创建一个RESTAPI。在我的系统中,我有两个表:类别和图像。表images具有列category\u id,该列是引用category表上列id的外键 类别表 图像表 在图像中模型类中,我做到了: class Images extends Model { protected $fillable = ['name']; protected $hidden = array('created_at', 'updated

我正在做我的第一个Laravel项目,我想为android应用程序创建一个RESTAPI。在我的系统中,我有两个表:
类别
图像
。表
images
具有列
category\u id
,该列是引用
category
表上列
id
的外键

类别
图像
表 在
图像中
模型类中,我做到了:

class Images extends Model
{
    protected $fillable = ['name'];
    protected $hidden = array('created_at', 'updated_at');

    public function category(){
        $this->belongsTo('App\Category');
    }
}
我还创建了
CategoryResource()
类作为:

class CategoryResource extends JsonResource

    {
          public function toArray($request)
        {
        return [
            'id'=> $this->id,
            'name' => $this->name,
        ];
        }
    }
因此,我使用API方法创建了一个
CategoryController
,并将路由配置为访问相应的函数。通过
GET
api/category/
url被重定向到我的控制器的
index
函数,函数如下:

public function index()
{
    $categories = Category::get();
    return CategoryResource::collection($categories);
}
有了它,我可以获得
类别
表数据,但我希望合并
用户
图像
表,并得到如下响应:

[
   {
      'id': 1,
      'name': 'category_name',
      'image': 'image_name'
   }
]

如何做到这一点?

首先在
类别
模型中为这样的图像添加一个
hasOne
关系

public function index()
{
    $categories = Category::with('image')->get();
    return CategoryResource::collection($categories);
}
类别模型

public function image(){  
    return $this->hasOne('App\Image');
}
现在在
类别资源中指定关系

class CategoryResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'=> $this->id,
            'name' => $this->name,
            'image' => new ImageResource($this->whenLoaded('image'))
        ];
    }
}
创建用于加载图像的
ImageResource

class ImageResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'=> $this->id,
            'name' => $this->image_name,
        ];
    }
}
最后,像这样在控制器中加载与渴望加载的关系

public function index()
{
    $categories = Category::with('image')->get();
    return CategoryResource::collection($categories);
}

@德克斯特,我想念你的问题。若您需要一对一,那个么只需在类别模型中添加一个hasOne关系,并在resource类中进行相应的更改。正因为如此,我在投票中被否决了。我会更新我的答案,这样未来的用户就不会problem@Dexter根据
hasOne
关系更新答案。谢谢你的理解并接受了我的回答。快乐编码
public function index()
{
    $categories = Category::with('image')->get();
    return CategoryResource::collection($categories);
}