duangongqiong6958 2016-01-23 11:22
浏览 94

使用带有laravel 5.1的dingo / APi + Fractal /变换器的laravel原始查询

I have an ArticleCommentsController with an index method

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);
    }
}

This is the transformer class

namespace App\Transformers;

use League\Fractal\TransformerAbstract;

class CommentTransformer extends TransformerAbstract{
    public function transform($comment)
    {
        return $comment; //simplified
    }
}

The response is the following error:

get_class() expects parameter 1 to be object, array given.

Obviously, i need to send an instance of the comment object when calling Fractal\transform but i don't know how to do that since laravel's raw queries only return an array or an instance of the QueryBuilder class.

  • 写回答

3条回答 默认 最新

  • dsijovl015728613 2016-01-23 16:56
    关注

    Sadly, the item method on the response object seems to require and object and not an array. Using the array method will work, but won't use any transformer you pass.

    So, I think you might get away using ArrayObject, as follow:

    return $this->response->item(new ArrayObject($comments), new CommentTransformer);

    Remember to put a use ArrayObject; at the top of the file.

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题