3

我在 laravel 5.3 中使用分形包。我有一个hasMany与视频有关系的播放器模型,所以一个播放器有很多视频。

播放器型号:

public function videos()
  {
      return $this->hasMany(Video::class);
  }

视频型号:

public function player()
{
    return $this->belongsTo(Player::class);
}

我正在尝试发送播放器数据并包含视频数据。这是控制器中的代码:

            $player  =  fractal()
                       ->item($player)
                       ->parseIncludes(['videos'])
                       ->transformWith(new PlayerTransformer)
                       ->toArray();

这是PlayerTransformer

<?php

namespace App\Transformer;

use App\Player;

class PlayerTransformer extends \League\Fractal\TransformerAbstract
{
    protected $availableIncludes = [
        'videos'
    ];

    public function transform(Player $player)
    {
        return [
          'id' => $player->id,
          'first_name' => $player->first_name,
          'last_name' => $player->last_name,
          'image' => $player->image_filename,
          'club' => $player->club,
          'birthday' => $player->birthday,
        ];
    }

    public function includeVideos(Player $player)
    {
        $videos = $player->videos()->where('processed', 1)->get();

        return $this->collection($videos, new VideoTransformer);
    }
}

我正在获取播放器数据,但我没有得到任何视频。这不起作用,但是如果尝试使用视频会更奇怪,我什至没有在其转换器中包含功能:

<?php

namespace App\Transformer;

use App\Video;

class VideoTransformer extends \League\Fractal\TransformerAbstract
{
    public function transform(Video $video)
    {
        return [
          'id' => $video->id,
          'uid' => $video->uid,
          'title' => $video->title,
          'image' => $video->getThumbnail(),
          'description' => $video->description,
          'views' => $video->viewCount(),
          'created_at' => $video->created_at->diffForHumans(),
        ];
    }
}

但是,当我尝试在其中包含玩家数据时,它会起作用:

              $videos = fractal()
                        ->collection($videos)
                        ->parseIncludes(['player'])
                        ->transformWith(new VideoTransformer)
                        ->toArray();

然后我尝试对视频转换器应用相同的设置并删除播放器转换器中的$availableIncludesand includeVideos ,但它再次在那里不起作用。我究竟做错了什么?

4

0 回答 0