如何在Laravel中获得belongsTo模型而不进行新的数据库请求


How to get the belongsTo model without making new db requests in Laravel?

Gallery.php:

<?php
class Gallery extends Eloquent {
    protected $visible = array(
        'title',
        'slug',
        'id'
    );
    public function coverImage() {
        return $this->belongsTo('Image', 'cover_image_id');
    }
}

Image.php:

<?php
class Image extends Eloquent {
    protected $visible = array(
        'id',
        'url'
    );
    protected $appends = array(
        'url'
    );
    public function gallery() {
        return $this->hasOne('Gallery', 'cover_image_id');
    }
    public function getUrlAttribute() {
        $slug = $this->gallery->slug;
        return '/images/' . $slug . '/' . $slug . '-' . $this->id . '.jpg';
    }
}

我想要的是:

return Response::json(Gallery::all()->with('coverImage')->get());

并且我希望每个coverImage都具有url属性。它有。。。但是Laravel正在查询每个库的数据库以获得其CCD_ 3,尽管由于CCD_。

如何避免?

您需要了解Eloquent关系是如何工作的。它们是而非双向。因此:

$model = Model::with('related')->first(); // loads related on model
$model->related; // eager loaded
// but
$model->related->model; // not eager loaded, so requires query

即使$model->model引用了DB中的同一行,最后一行也是真的。

也就是说,你需要在图像上急切地加载gallery

return Response::json(Gallery::with('coverImage.gallery')->get());