自动预加载?

Automatic eager loading?

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

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

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

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

并且仍然渴望加载image

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

protected $with = array('image');

这应该可以解决问题。

$with 属性列出了每个查询都应该预先加载的关系。

这是另一个非常有效的解决方案!

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();..