Laravel 自动加载?

Laravel 自动加载?,laravel,laravel-4,laravel-5,Laravel,Laravel 4,Laravel 5,而不是像这样做(我在整个网站上做了几十次): 当调用with('user')时,是否可以自动调用with('image')?所以最后,我可以做的只是: $posts = Post::with('user') ->get(); 并且仍然渴望加载图像?在您的模型中添加以下内容: protected $with = array('image'); 这就应该奏效了 带有属性的$列出了每个查询都应该加载的关系。这里是另一个非常有效的解决方案 class Post extends Mode

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

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

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

并且仍然渴望加载
图像

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

protected $with = array('image');
这就应该奏效了


带有属性的$列出了每个查询都应该加载的关系。

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

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
$posts=Post::with('user')->get()当您不想再调用以检索图像时

Post::with('user','image')或在Post类上编写一个方法?效果很好。谢谢,伙计。
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();