【问题标题】:Automatic eager loading?自动急切加载?
【发布时间】:2015-10-06 12:55:22
【问题描述】:

而不是做这样的事情(我在整个网站上做了几十次):

$posts = Post::with('user')
    ->with('image')
    ->get();

是否可以在调用with('user') 时自动调用with('image')?所以最后,我可以这样做:

$posts = Post::with('user')
    ->get();

并且仍然渴望加载image

【问题讨论】:

  • Post::with('user','image') 还是在 Post Class 上写一个方法?

标签: laravel laravel-4 laravel-5


【解决方案1】:

这里是另一个像魅力一样的解决方案!

class Post extends Model {

    protected $table = 'posts';
    protected $fillable = [ ... ];

    protected $hidden = array('created_at','updated_at');

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

    public function userImage()
    {
        return $this->belongsTo('App\Models\User')->with('image');
    }

}

$posts = Post::with('userImage')->get();

使用它,您仍然可以使用您的用户帖子$posts = Post::with('user')->get();,只要您不想再调用来检索图像..

【讨论】:

    【解决方案2】:

    在您的模型中添加以下内容:

    protected $with = array('image');
    

    这应该可以解决问题。

    $with 属性列出了应该随每个查询立即加载的关系。

    【讨论】:

    • 效果很好。谢谢,伙计。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多