首页 > 解决方案 > 解析具有变形关系的资源类

问题描述

问题

我有具有变形关系的模型,并且那些不同类型的关系具有完全不同的 json 资源要返回。所以我试图找到一种方法来解决正确的关系类并将其与基本模型的资源一起返回。

例如,如果我有评论和变形关系“可评论”,其中包含汽车和司机的模型实例。现在,如果我请求一些评论,我将能够返回存储到 CarResource 或 PeopleResource 中的正确 json 响应。

{
    id: 1,
    text: 'A comment',
    commentable_type: 'Car', // could be car or driver
    commentable_data: {
        model: 'Ford',
        year: 2019
    },

    id: 2,
    text: 'An another comment',
    commentable_type: 'Driver',
    commentable_data: {
        name: 'Jon Doe',
        active: true
    },
}

试图解决

我尝试使用以下功能,但出现错误。

public function toArray($request)
{
    $modelClass = app(__NAMESPACE__ . '\\' . class_basename($this->commentable) . 'Resource');

    return [
        'id' => $this->id,
        'text' => $this->text,
        'commentable_type' => class_basename($this->commentable),
        'commentable_data' => new $modelClass($this->commentable),
    ];
}

如果解决的课程不存在,我当然会得到

反射异常 (-1)

类 App\Http\Resources\CarResource 不存在

但是如果该类存在,我会收到以下错误

照亮\合同\容器\ BindingResolutionException

类 Illuminate\Http\Resources\Json\JsonResource 中无法解析的依赖解析 [Parameter #0 [ $resource ]]

问题

你怎么看?您有任何解决方案或建议,例如如何更好地管理这个问题?

标签: phplaraveleloquent

解决方案


好的,我通过深入研究 Laravel 找到了解决方案。服务容器是我的朋友。就像BindingResolutionException说我需要$resource使用函数为解析器提供参数makeWith()

$modelClass = app()->makeWith(__NAMESPACE__ . '\\' . class_basename($this->barcodable) . 'Resource', [
    'resource' => $this->barcodable
]);

但是,请让我知道是否有人对改进这一点有任何想法。


推荐阅读