在https://github.com/thephpleague/fractal.
我有两张桌子,Property和Weeks。每一处房产都有好几个星期。使用Fractal,我可以返回我的财产项目和周的集合。我想做的是使用parseIncludes,这样周的返回是可选的。
PropertyTransformer.php
<?php
namespace AppTransformer;
use AppModelsProperty;
use LeagueFractalTransformerAbstract;
class PropertyTransformer extends TransformerAbstract
{
protected $availableIncludes = [
'week'
];
public function transform(Property $property)
{
return [
'id' => (int) $property['PropertyID'],
'PropertyName' => $property['PropertyName'],
'ExactBeds' => (int) $property['ExactBeds'],
'weeks' => $property->week
];
}
/**
* Include Week
*
* @return LeagueFractalItemResource
*/
public function includeWeek( Property $property )
{
$week = $property->week;
return $this->item($week, new WeekTransformer);
}
}
WeekTransformer.php
<?php
namespace AppTransformer;
use AppModelsWeek;
use LeagueFractal;
class WeekTransformer extends FractalTransformerAbstract
{
public function transform(Week $week)
{
return [
'Week' => $week['week'],
'Available' => $week['available'],
'Price' => (int) $week['price'],
];
}
}
我的PropertyController.php
<?php namespace AppHttpControllersApiv1;
use AppHttpRequests;
use AppModelsWeek;
use IlluminateSupportFacadesResponse;
use AppModelsProperty;
use LeagueFractal;
use LeagueFractalManager;
use LeagueFractalResourceCollection as Collection;
use LeagueFractalResourceItem as Item;
use AppTransformerPropertyTransformer;
class PropertyController extends AppHttpControllersController {
public function show($id)
{
$property = Property::with('bedroom')->with('week')->find($id);
$fractal = new FractalManager();
if (isset($_GET['include'])) {
$fractal->parseIncludes($_GET['include']);
}
$resource = new FractalResourceItem($property, new PropertyTransformer);
//$resource = new FractalResourceCollection($properies, new PropertyTransformer);
return $fractal->createData( $resource )->parseIncludes('weeks')->toJson();
}
我在parseIncludes上得到以下错误:-
在class\League \Fractal\Scope 中找不到方法"parseIncludes"
我遵循这里的变压器指南-http://fractal.thephpleague.com/transformers/
我想我在这里的某个地方出错了,上面写着:-
除非调用Manager::parseIncludes()方法:,否则这些include将可用,但永远无法请求
<?php
use LeagueFractal;
$fractal = new FractalManager();
if (isset($_GET['include'])) {
$fractal->parseIncludes($_GET['include']);
}
如果我删除parseIncludes,我不会得到错误,我也会用我的周集合获得我的属性数据,但是?include=week不适用于可选获取。
您的问题在这一行:return $fractal->createData( $resource )->parseIncludes('weeks')->toJson();
createData()
返回LeagueFractalScope
,它没有parseInlcudes
方法。
您已经在此处调用了parseIncludes
:
if (isset($_GET['include'])) {
$fractal->parseIncludes($_GET['include']);
}
因此,只需在return
语句中删除对它的第二个调用:return $fractal->createData($resource)->toJson();