You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何在MealResource中调用TagResource返回数据?

问题描述

我尝试寻找解决方案但未果。由于存在TagTranslations表,且已在TagResource中处理该表的翻译数据,我希望在MealResource中调用TagResource返回标签数据。

模型关联已正确配置:Meal与Tag通过meal_tags中间表关联,TagTranslation属于Tag模型。

我的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 (已尝试TagResource::collection()和new TagResource()但无效)


        ];
    }

请问如何正确填充MealResource中tags字段的内容?


解决方案

1. 正确填充tags字段

首先确认Meal模型中已定义与Tag的多对多关联:

public function tags()
{
    return $this->belongsToMany(Tag::class, 'meal_tags');
}

在MealResource的toArray方法中,直接使用TagResource::collection()传入关联的标签集合即可:

'tags' => TagResource::collection($this->tags)

2. 优化冗余代码与查询效率

  • 简化TagResource中的翻译查询:$this->translations已经是当前标签关联的翻译集合,无需额外通过tag_id过滤,直接取第一个即可:
public function toArray($request)
{
    $translation = $this->translations->first();
    return [
        'id' => $this->id,
        'title' => $translation->title,
        'slug' => $translation->slug,
    ];
}
  • 避免N+1查询问题:在查询Meal数据时,预加载所有需要的关联关系,提升性能:
$meals = Meal::with('tags.translations', 'translations', 'category.translations')->get();
return MealResource::collection($meals);

内容的提问来源于stack exchange,提问作者PhantomPhreak1995

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:10:51