简体   繁体   中英

Laravel Resource return value from another Resource?

I tried to find a solution here but nothing worked. I want to return values from TagResource using MealResource because I have TagTranslations table and I'm getting the data from the table with translations in TagResource.

Relationships are correctly formed, meal and tag models are connected via meal_tags table and tagtranslations belongsTo Tag::class.

I used TagResource like this:

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,
            ];
    }
}

and MealResource like this:

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


        ];
    }
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),
        ];
    }

If all the Relationships namings/mappings are correct then this will work.And please make sure that model are perfectly mapped respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM