我正在为我的网络应用程序使用Laravel框架,使用雄辩的数据模型和Fractal来转换一些数据。
我想使用分形的parseIncludes
功能,但是尽管遵循了文档,我似乎无法使其工作。
这是我的代码:
StudentTransformer.php
class StudentTransformer extends Fractal\TransformerAbstract
{
protected $availableIncludes = [
'course'
];
public function transform(Student $student)
{
return [
'name' => $student->name,
// other attributes
];
}
public function includeCourse(Student $student)
{
$course = $student->course;
return $this->item($course, new CourseTransformer);
}
}
CourseTransformer.php
class CourseTransformer extends Fractal\TransformerAbstract
{
public function transform(Course $course)
{
return [
'name' => $course->name
// other attributes
];
}
}
在我的一个控制器中:
$student = App\Models\Student::first();
$fractal = new \League\Fractal\Manager();
$fractal->parseIncludes('/student?include=course');
$fractal->setSerializer(new \League\Fractal\Serializer\ArraySerializer());
$response = new \League\Fractal\Resource\Item($student, new \App\Transformers\Models\StudentTransformer);
return response()->json($fractal->createData($response)->toArray());
此外,当我从StudentTransformer中删除availableIncludes
并改为使用defaultIncludes
时,如下所示:
protected $defaultIncludes = [
'course'
];
它工作正常吗?!不明白为什么!任何帮助将不胜感激。
答案 0 :(得分:1)
修正了它。为了他人的利益,问题在于:
$fractal->parseIncludes('/student?include=course');
应该是:
$fractal->parseIncludes('course');