我想,当我将对象序列化为JSON时,自动获取userreplies是可行的,但是重写toArray真的是正确的方法吗?

<?php

class Post extends Eloquent
{
    protected $table = 'posts';
    protected $fillable = array('parent_post_id', 'user_id', 'subject', 'body');

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function replies()
    {
        return $this->hasMany('Post', 'parent_post_id', 'id');
    }

    public function toArray()
    {
        $this->load('user', 'replies');
        return parent::toArray();
    }
}

推荐答案

Instead of overriding toArray() to load user and replies, use $with.

下面是一个例子:

<?php

class Post extends Eloquent
{
    protected $table = 'posts';
    protected $fillable = array('parent_post_id', 'user_id', 'subject', 'body');

    protected $with = array('user', 'replies');


    public function user()
    {
        return $this->belongsTo('User');
    }

    public function replies()
    {
        return $this->hasMany('Post', 'parent_post_id', 'id');
    }

}

Also, you should be using toArray() in your controllers, not your models, like so:

Post::find($id)->toArray();

Hope this helps!

Laravel相关问答推荐

为什么Laravel在API请求时返回BadMethodCallException?

Laravel 模型事件:delete() 不会从存储中删除文件

如何通过 Controller 访问 Laravel 中 Model 的值?

如何更改 laravel sanctum 返回message: Unauthenticated.

Laravel init 查询多种用途

Eloquent的条件过滤器

RouteCollection.php 第 219 行中的 MethodNotAllowedHttpException

Laravel 5.4 - 如何为同一个自定义验证规则使用多个错误消息

Laravel - 排序的集合输出不是数组

Laravel timestamps() 不会创建 CURRENT_TIMESTAMP

laravel 预期响应代码 250 但得到代码530

这个上下文的流程应该是怎样的? (根据 Select 的付款方式,将处理付款的代码放在哪里?)

如何在中间件 Laravel 中获取请求的控制器和操作的名称

如何从 Windows 命令提示符在 Laravel 中运行 PHPUnit

将图标添加到 Laravelcollective 提交按钮

数组的旧输入?

Laravel Blade - 如果满足条件,则添加一个类

如何使用 Laravel 测试授权重定向?

Laravel Queue,Beanstalkd vs Database,有什么区别?

Laravel/PHPUnit:断言 json 元素存在而不定义值