我有一个带有索引方法的ArticleCommentsController
class ArticleCommentsController extends BaseController
{
public function index($id)
{
$comments = DB::table('comments')
->leftJoin('users', 'users.id', '=', 'comments.user_id')
->where('comments.article_id', '=', $id)
->get();
return $this->response->item($comments, new CommentTransformer);
}
}这是transformer类
namespace App\Transformers;
use League\Fractal\TransformerAbstract;
class CommentTransformer extends TransformerAbstract{
public function transform($comment)
{
return $comment; //simplified
}
}响应为以下错误:
get_class() expects parameter 1 to be object, array given.显然,在调用Fractal\transform时,我需要发送comment对象的一个实例,但我不知道该如何做,因为laravel的原始查询只返回一个数组或QueryBuilder类的一个实例。
发布于 2016-01-24 00:56:20
遗憾的是,response对象上的item方法似乎需要and对象,而不是数组。使用array方法将会起作用,但不会使用您传递的任何转换器。
因此,我认为您可以使用ArrayObject,如下所示:
return $this->response->item(new ArrayObject($comments), new CommentTransformer);
记住在文件的顶部放置一个use ArrayObject;。
发布于 2016-09-25 10:04:46
这是很久以前的事了,但如果我失去了记忆,我会在将来为这个人或其他人或我自己写答案哈哈哈
class ArticleCommentsController extends BaseController
{
public function index($id)
{
$comments = DB::table('comments')
->leftJoin('users', 'users.id', '=', 'comments.user_id')
->where('comments.article_id', '=', $id)
->get();
return $this->response->collection(Collection::make($comments), new CommentTransformer);
}
}当然,您需要将此代码添加到控制器ArticleCommentsController中
// Dingo
use Dingo\Api\Routing\Helpers;
//Convert query to collective
use Illuminate\Support\Collection;
//Transformers for API
use App\Transformers\CommentTransformer;在你的函数之前,在你的控制器里
//Use for Dingo Helpers
use Helpers;总而言之:
<?php
namespace App\Http\Controllers;
use Response;
use App\User;
use App\Http\Requests;
use Illuminate\Http\Request;
// Dingo
use Dingo\Api\Routing\Helpers;
//Convert query from LMS lbrary to collective
use Illuminate\Support\Collection;
//Transformers for API
use App\Transformers\CommentTransformer;
class ArticleCommentsController extends BaseController
{
//Use for Dingo Helpers
use Helpers;
public function index($id)
{
$comments = DB::table('comments')
->leftJoin('users', 'users.id', '=', 'comments.user_id')
->where('comments.article_id', '=', $id)
->get();
return $this->response->collection(Collection::make($comments), new CommentTransformer);
}
}致敬!我希望这对将来的其他人有所帮助:
发布于 2017-05-05 14:54:56
执行以下步骤,它就能解决问题:
1.change
return $this->response->item($comments, new CommentTransformer);
至
return $this->response->collection(Collection::make($comments), new CommentTransformer);
2. 2.Transfomer类
namespace App\Transformers;
use League\Fractal\TransformerAbstract;
class CommentTransformer extends TransformerAbstract{
public function transform($comment)
{
return [
'id' => $comment->id,
...
];
}
}https://stackoverflow.com/questions/34962795
复制相似问题