繁体   English   中英

Laravel 9 - Eloquent model:试图加载自我 Z20F35E630DAF44DBFA4C3F68F539 递归父母

[英]Laravel 9 - Eloquent model : Trying to load self model parents recursively

I'm trying to migrate a Laravel 5 API with MySQL 5.7 to a Laravel 9 API with MySQL 8.

几乎一切都运行良好,除了一些尝试以递归方式加载数据的查询。

在 Laravel 5 上,我想出了以下解决方案: 递归 Eloquent 模型| Laravel ORM 从自引用表得到 N 级层次结构 JSON

它就像一个魅力,但在 Laravel 9 上,我从 Apache 收到 HTTP 500 错误,它在日志中告诉我以下错误:

PHP 致命错误:允许的 memory 大小为 134217728 字节用尽(试图分配 262144 字节)

I tried at first to increase the memory in php.ini, but it was getting worst as the server was getting very laggy, so I had to restart Apache and go back with the 128M default value. 同样在我的 Laravel 5 环境中,我不需要增加 memory。

我也怀疑 MySQL 8 升级涉及到这个问题,但是通过连接到我的 MySQL 5.7 数据库,我遇到了同样的问题,所以我认为它来自 ZA5C95B86291EA2920Z 加载版本关系的方式。

这是我的 Model 代码:

<?php
  namespace App\Models\Consommation;

  use Illuminate\Database\Eloquent\Model;

  class ConsoRequestAttribut extends Model
  {
    protected $table = 'conso_request_attribut';
    public $incrementing = false;
    protected $primaryKey = 'id_attribut';
    public $timestamps = false;

    const ERROR_DELETE_ATTRIBUTE = 1;
    const SUCCESS_DELETE_ATTRIBUTE = 0;

    protected $fillable = [
        'id_attribut',
        'code_type_attribut',
        'valeur',
        'id_parent_attribut'
    ];

    public function parent_attribut() {
        return $this->belongsTo('App\Models\Consommation\ConsoRequestAttribut', 'id_parent_attribut', 'id_attribut');
    }

    public function parent() {
        return $this->parent_attribut()->with('parent');
    }

    ...
   }

因此,在我的 Laravel 9 应用程序上,如果我删除我的parent() function 中的->with('parent') ,则返回查询结果并且我没有 500 Z293C9EA246FF9985DC6F62A6 递归错误,所以我认为问题是 789866F62A6加载。

任何想法?

谢谢

最好像这样调用嵌套关系:

public function parent() {
    return $this->with('parent_attribut.parent');
}

我没有成功使用我的ConsoRequestAttribut model 递归加载父实体,因为我仍然遇到相同的 memory 问题。 所以它并没有真正“解决”。

作为替代方案,在我的ConsoRequestAttributRepository class 中,我制作了一个 function 以递归方式加载实体的父级,效果很好:

public function retrieveRecursivelyConsoRequestAttributeParent(ConsoRequestAttribut $attribut)
{
    $parent = ConsoRequestAttribut::where('id_attribut', $attribut->id_parent_attribut)
        ->first();

    $attribut->parent = $parent;

    if($parent->id_parent_attribut != null)
        $this->retrieveRecursivelyConsoRequestAttributeParent($parent);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM