渴望负载有很多& belongsTo(循环引用/无限循环) [英] Eager load hasMany & belongsTo (circular reference/infinite loop)

查看:152
本文介绍了渴望负载有很多& belongsTo(循环引用/无限循环)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遇到一个简单的问题:

I'm running into what I believe is a simple problem:


  • 我有一个属性对象,有许多 图像 s

  • / code> 属于 属性 ...(反向关系)

  • I have a Property object that has many Images
  • Image belongs to Property... (inverse relation)

我的问题是,我想在 Property images() c>模型和图像模型中的属性()。为了做到这一点,我只需要在文档中解释一下 $ $。

My problem is that I want to eager load both the images() on the Property model and the property() on the Image model. To do so, I just setup a $with property as explained in the docs.

我的属性 model:

class Property extends EloquentModel {
    protected $with = ['images'];

    public function images()
    {
        return $this->hasMany(Image::class);
    }
}

我的图像模型:

class Image extends EloquentModel {
    protected $with = ['property'];

    public function property()
    {
        return $this->belongsTo(Property::class);
    }

    public function getAlt()
    {
        return $this->property->title;
    }
}

但执行时:

$prop = Property::find(203);

这将导致无限循环(php分段错误)。必须有一些我无法找到的循环引用:

This results in an infinite loop (php segmentation fault). There must be some kind of circular reference that I am not able to locate:

[1]    85728 segmentation fault

更新

我发现最简单的解决方法:

This is the simplest "Workaround" I found:

// Property.php
public function setRelation($relation, $value)
{
    if ($relation === 'images') {
        foreach ($value as $image) {
            $image->setProperty($this);
        }
    }
    return parent::setRelation($relation, $value);
}

这个,以及删除 code>侧面的关系...

This, as well as removing the Image side of the relationship...

class Image extends EloquentModel {
    // protected $with = ['property'];

    // public function property()
    // {
    //     return $this->belongsTo(Property::class);
    // }


推荐答案

找到一个属性,该属性渴望加载它所有的所有图像,每个图像eager加载属性属性,这是您尝试找到的属性,这将再次开始渴望加载所有的图像。等等...

When you try to find a Property, that property eager loads all the images it has and every Image eager loads the property it belongs to, which is the property you try to find, which will again start to eager load all the images it has. etc...

我解决这个问题的方式是不要急于加载模型,而是通过在调用模型时急切加载。

The way I would resolve this problem is by not eager loading inside the models, but by eager loading when calling the models.

所以使用以下内容:

$prop = Property::with('images')->find(203);

同时在Property模型中移除此行:

while removing this line in the Property model:

protected $with = ['images'];

图像模型中的这一行:

protected $with = ['property'];

我希望这个解决方案适合你。

I hope this solution works for you.

这篇关于渴望负载有很多& belongsTo(循环引用/无限循环)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆