【问题标题】:Laravel Resource return value from another Resource?Laravel 资源从另一个资源返回值?
【发布时间】:2023-01-27 06:06:25
【问题描述】:

我试图在这里找到解决方案,但没有任何效果。我想使用 MealResource 从 TagResource 返回值,因为我有 TagTranslations 表,并且我正在从表中获取带有 TagResource 翻译的数据。

关系正确形成,膳食和标签模型通过 meal_tags 表和 tagtranslations belongsTo Tag::class 连接。

我像这样使用 TagResource:

class TagResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $translation = $this->translations->where('tag_id', $this->id)->first();
            return 
            [
                'id' => $this->id,
                'title' => $translation->title,
                'slug' => $translation->slug,
            ];
    }
}

和 MealResource 是这样的:

public function toArray($request)
    {
        $translation = $this->translations->where('meal_id', $this->id)->first();
        $category_translation = $this->category->translations->where('category_id', $this->category->id)->first();


        return [
            'id' => $this->id,
            'title' => $translation->title,
            'decription' => $translation->description,
            'category' => [
                'id' => $this->category->id,
                'title' => $category_translation->title,
                'slug' => $category_translation->slug,
            ],
            'tags' => FILL IN THE BLANK (have used TagResource:collection() and new TagResource()) and didnt work


        ];
    }

【问题讨论】:

  • 如果您想在 MealResource 标签中设置 Meal 模型标签,您可以通过 Meal 模型的关系发送

标签: laravel api eloquent resources eloquent-relationship


【解决方案1】:
public function toArray($request)
    {
        $translation = $this->translations->where('meal_id', $this->id)->first();
        $category_translation = $this->category->translations->where('category_id', $this->category->id)->first();

        return [
            'id' => $this->id,
            'title' => $translation->title,
            'decription' => $translation->description,
            'category' => [
                'id' => $this->category->id,
                'title' => $category_translation->title,
                'slug' => $category_translation->slug,
            ],
            'tags' => TagResource::collection($this->tags),
        ];
    }

如果所有关系命名/映射都是正确的,那么这将起作用。请确保模型分别完美映射。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 2022-07-26
    • 1970-01-01
    • 2018-12-10
    • 2018-10-18
    • 1970-01-01
    • 2014-05-02
    相关资源
    最近更新 更多