L03 Laravel 教程 - 实战构架 API 服务器 在 7.3 回复列表中,不能进行嵌套关联返回信息

单独的使用 include=topic、include=user 都可以返回内容,但是include=topic.user 时候只有 topic 的内容没有 user 的嵌套内容

L03 Laravel 教程 - 实战构架 API 服务器 在 7.3 回复列表中,不能进行嵌套关联返回信息

Transformer

namespace App\Transformers;

use App\Models\Reply;
use League\Fractal\TransformerAbstract;

class ReplyTransformer extends TransformerAbstract
{

    protected $availableIncludes = ['user', 'topic'];

    public function transform(Reply $reply){
        return [
            'id' => $reply->id,
            'user_id' => (int) $reply->user_id,
            'topic_id' => (int) $reply->topic_id,
            'content' => $reply->content,
            'created_at' => $reply->created_at->toDateTimeString(),
            'updated_at' => $reply->updated_at->toDateTimeString(),
        ];
    }

    public function includeUser(Reply $reply) {
        return $this->item($reply->user, new UserTransformer());
    }

    public function includeTopic(Reply $reply) {
        return $this->item($reply->topic, new TopicTransformer());
    }

}

Controller

 public function userIndex(User $user) {
        $replies = $user->replies()->paginate(10);

        return $this->response->paginator($replies, new ReplyTransformer());
    }

URL

http://larabbs.test/api/users/22/replies?include=topic.user

Topic Model

L03 Laravel 教程 - 实战构架 API 服务器 在 7.3 回复列表中,不能进行嵌套关联返回信息

User Model

L03 Laravel 教程 - 实战构架 API 服务器 在 7.3 回复列表中,不能进行嵌套关联返回信息

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
liyu001989
最佳答案

@Soner 那应该是代码的问题,确认一下 TopicTransformer 有 includeUser 以及 $availableIncludes 正确。 你看一下查询的 sql 日志,预加载正确没有。

4年前 评论
讨论数量: 4
liyu001989

laravel 和 dingo 的版本是多少。跟 github 上的项目代码对比一下,确定一下不是代码的问题。再来看看是不是 dingo 的 bug。

最新版本确实有预加载的 bug https://github.com/dingo/api/issues/1645, 不过貌似应该能返回数据

4年前 评论
liyu001989

@Soner 那应该是代码的问题,确认一下 TopicTransformer 有 includeUser 以及 $availableIncludes 正确。 你看一下查询的 sql 日志,预加载正确没有。

4年前 评论

@liyu001989 我回到第六章看了下,确实是 TopicTransformer 忘记写 includes 了,粗心了,非常感谢

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!