gpt4 book ai didi

Laravel 分形转换器 - 没有包含

转载 作者:行者123 更新时间:2023-12-05 07:40:11 24 4
gpt4 key购买 nike

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

播放器模型:

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

视频模型:

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

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

            $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();

然后我尝试应用与视频转换器相同的设置并删除播放器转换器中的 $availableIncludesincludeVideos,但它再次没有在那里工作。我做错了什么?

最佳答案

我在没有身份验证的情况下执行 get 来测试我的 Controller ,它给出了错误:

PHP fatal error :第 8 行/app/Transformers/CustomerCategoryTransformer.php 中的 App\Transformers\CustomerCategoryTransformer::$availableIncludes 类型必须是数组(如类 League\Fractal\TransformerAbstract 中)

我注释掉了这行:

protected $defaultIncludes = [];
protected $availableIncludes = [];

我的代码:

<?php

namespace App\Transformers;

use App\Models\CustomerCategory;
use League\Fractal\TransformerAbstract;

class CustomerCategoryTransformer extends TransformerAbstract
{
// protected $defaultIncludes = [];

// protected $availableIncludes = [];

public function transform(CustomerCategory $model)
{
return [
'id' => $model->id,
'uuid' => $model->uuid,
'seq' => $model->seq,
'slug' => $model->slug,
'name' => $model->name,
'active' => $model->active,
'created_at' => $model->created_at->toDateTimeString(),
'updated_at' => $model->updated_at->toDateTimeString(),
];
}
}

关于Laravel 分形转换器 - 没有包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46395369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com