【问题标题】:Laravel Eloquent: How to automatically fetch relations when serializing through toArray/toJsonLaravel Eloquent:如何在通过 toArray/toJson 序列化时自动获取关系
【发布时间】:2014-03-02 14:44:40
【问题描述】:

我认为这适用于在我将对象序列化为 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();
    }
}

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

    不要覆盖toArray() 来加载用户和回复,而是使用$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');
        }
    
    }
    

    另外,你应该在你的控制器中使用toArray(),而不是你的模型,就像这样:

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

    希望这会有所帮助!

    【讨论】:

    • 太棒了。我希望有一个更聪明的方法。我正在利用 Route::model 方法自动获取正确的模型并将其传递给我的控制器。这是一个请求 JSON 的 AJAX 调用,所以当我在控制器方法中返回模型时,Laravel 会自动处理 toJson 调用:-) pastebin.com/5MMwiXS2
    • 这对我很有帮助——谢谢!您是否知道$with 是否记录在任何地方?我在 Laravel 文档中找不到它,但它似乎可以解决问题。
    • 好像只有in the source
    • 此解决方案将始终加载关系。不仅在序列化时。请注意其他用例的潜在开销。
    • 我见过几个使用 find 加载实体的例子,集合呢,比如使用 get 或 paginate!
    【解决方案2】:

    我必须提交一个新的答案,因为我是一个普通人。对于像我一样在 Google 上找到此内容的人来说,更合适的方法是避免使用 protected $with(如果您不需要),而是将 with() 调用移至您的检索。

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

    然后您可以根据需要将 Post 调用修改为预加载:

    Post::with('user','replies')->find($id)->toArray();
    

    这样,您就不会在每次获取记录时都包含不需要的数据,如果您不需要的话。

    【讨论】:

    • 这并没有回答序列化时自动获取的问题。
    • 上述答案,特别是Post::with('user','replies')-&gt;find($id)-&gt;toArray(); 将加载包含关系的帖子,而无需按照要求覆盖 toArray。此外,这只是对 Jake 发布的已接受答案的修订,以提高效率,因此您不必在每次实例化帖子时都加载用户和回复。
    猜你喜欢
    • 2021-10-05
    • 2015-04-10
    • 2021-09-11
    • 1970-01-01
    • 2015-08-21
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多