暂时算是解决了,写一下解决的办法。谁有更好的办法可以和我说下。
第一个问题是区分为两个transformer,不多说,第二个关联多个评论的解决代码为:
NewsTransformer.php
public function transform($item)
{
return [
'id' => $item->id,
'title' => $item->title,
'created_at' => $item->created_at . '',
'content' => $item->content,
'comments' => $this->transformComments($item->comments()->take(3)->get()),
'comments_count' => $item->comments->count(),
];
}
public function transformComments($comments)
{
//这里不可以使用array_map,转换为数组后会导致NewsCommentsTransformer里面获取错误。
$array = [];
foreach ($comments as $news_comments){
$array[count($array)] = (new NewsCommentsTransformer)->transform($news_comments);
}
return $array;
}
NewsCommentsTransformer.php
public function transform($item)
{
return [
'id' => $item->id,
'content' => $item->content,
'userid' => $item->user_id,
'username' => $item->user->name,
'created_at' => $item->created_at . ''
];
}