Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在不向Laravel发出新的db请求的情况下获取belongsTo模型?_Php_Laravel_Eloquent - Fatal编程技术网

Php 如何在不向Laravel发出新的db请求的情况下获取belongsTo模型?

Php 如何在不向Laravel发出新的db请求的情况下获取belongsTo模型?,php,laravel,eloquent,Php,Laravel,Eloquent,Gallery.php: <?php class Gallery extends Eloquent { protected $visible = array( 'title', 'slug', 'id' ); public function coverImage() { return $this->belongsTo('Image', 'cover_image_id'); } }

Gallery.php:

<?php

class Gallery extends Eloquent {

    protected $visible = array(
        'title',
        'slug',
        'id'
    );

    public function coverImage() {
        return $this->belongsTo('Image', 'cover_image_id');
    }

}
我希望每个
coverImage
都有
url
属性。它有。。。但是Laravel正在查询每个库的数据库,以获取其
slug
,尽管由于
with()
方法,它有库


如何避免它?

你需要了解雄辩的关系是如何运作的。它们不是双向的。因此:

$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
引用了数据库中的同一行,最后一行也是正确的

也就是说,您需要在图像上快速加载

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

只是一个想法,但画廊或图像中的一个类不应该和另一个有一个关系,而不是两个类都有一个归属吗?@Adimeus你们是对的。我已经编辑了我的问题。不幸的是,这并不能解决问题。我已经为每个
选择了
中的
封面图片id=?限制1”。好的,这会更好,但会产生两个相同的查询。这是实现我所需要的最好也是唯一的方法吗?这是最简单的解决方案,只需要几个字母的代码。如果您担心性能,请使用join。
$model = Model::with('related')->first(); // loads related on model

$model->related; // eager loaded

// but
$model->related->model; // not eager loaded, so requires query
return Response::json(Gallery::with('coverImage.gallery')->get());