[英]Use laravel raw queries with dingo/APi + Fractal/transformers with laravel 5.1
我有一个带有索引方法的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);
}
}
这是变压器课
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时需要发送注释对象的实例,但是我不知道该怎么做,因为laravel的原始查询仅返回数组或QueryBuilder类的实例。
可悲的是, response
对象上的item
方法似乎需要和对象而不是数组。 使用array
方法可以使用,但不会使用您传递的任何转换器。
因此,我认为您可能会像下面这样使用ArrayObject
:
return $this->response->item(new ArrayObject($comments), new CommentTransformer);
记住要use ArrayObject;
在文件的顶部。
这是很久以前了,但是如果我失去了记忆,我将来会为这个人或其他人或我写答案。
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);
}
}
问候!,希望以后对其他人有帮助:D
执行以下步骤,即可解决:
1.改变
return $this->response->item($comments, new CommentTransformer);
至
return $this->response->collection(Collection::make($comments), new CommentTransformer);
2.Transfomer类
namespace App\Transformers;
use League\Fractal\TransformerAbstract;
class CommentTransformer extends TransformerAbstract{
public function transform($comment)
{
return [
'id' => $comment->id,
...
];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.