【问题标题】:Problem using Eager Loading in a Eloquent Model在 Eloquent 模型中使用急切加载的问题
【发布时间】:2019-07-30 13:36:16
【问题描述】:

我有 2 个模型及其关系。第一类称为“Documento”:

class Documento extends Model
{
    protected $table = 'documento';
    protected $primaryKey = 'cod_documento';

    public function emisor()
    {
        return $this->belongsTo('App\Emisor', 'cod_emisor', 'cod_emisor');
    }
}

第二个叫做'Emisor':

class Emisor extends Model
{
    protected $table = 'emisor';
    protected $primaryKey = 'cod_emisor';

    public function documentos()
    {
        return $this->hasMany('App\Documento', 'cod_emisor', 'cod_emisor');
    }
}

模型关系是一对多的(一个发射器有很多文档,一个文档只有一个发射器)。

在 Thinker 中,我尝试从文档中获取发射器,并且效果很好:

>>> Documento::find(1)->emisor->name
=> "Emisor Name"

但是当我尝试在文档中进行 Eager Loading the emisor 时,“失败”:

>>> Documento::find(1)->with('emisor')->count();
=> 94041

我期望一个结果,但查询返回 94041 个文档。

为什么会这样?如何获得一个带有嵌套发射器的文档?

【问题讨论】:

    标签: laravel-5 eloquent eager-loading laravel-5.7 eloquent-relationship


    【解决方案1】:

    交换find()with()

    $documento = Documento::with('emisor')->find(1);
    

    或者使用lazy eager loading:

    $documento = Documento::find(1)->load('emisor');
    

    使用现有模型实例:

    $documento->load('emisor');
    

    您会得到这个意外结果,因为Documento::find(1)->with('emisor') 创建了一个新查询来查询所有 Documento 条目。因此,94041 的总数。

    【讨论】:

    • 但是,如果我在控制器的 show 方法中使用您的第一个解决方案(使用模型绑定),请始终返回第一个文档: public function show(Documento $documento) { return $documento->with ('emisor')->find(1); } ```
    • 对模型实例使用第二个选项:$documento->load('emisor');
    猜你喜欢
    • 2013-06-10
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 2021-10-02
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    相关资源
    最近更新 更多