首頁  >  問答  >  主體

重寫後的標題為:What causes a "possible infinite loop" when accessing another model attribute in an appended attribute of a model?

<p>我的 <strong>Laravel 9</strong> 應用程式有兩個模型: <code>brand</code> 模型和 <code>product</code> 模型。每<code>product</code> 屬於一個<code>brand</code>,而一個<code>brand</code> 又屬於多個<code>products</code>(1: n 關係)。 <code>product</code> 模型應提供一個名為 <code>title_medium</code> 的「計算」(附加)屬性,該屬性根據請求連接品牌標題和產品標題。 </p> <p>一旦我嘗試在產品模型的<code>getTitleMediumAttribute()</code> 方法中訪問<code>$this->brand</code> , <code>xdebug</code>/code> , <code>xdebug</code>就會拋出<code>possibleInfiniteloop</code> 異常並取消執行(N次迭代後) 。我認為這與關係和加載序列(渴望加載)有關,但到目前為止我找不到解決方案。 </p> <h2>品牌模型</h2> <p><code>brand</code> 模型有屬性 <code>title</code> 並且有許多屬於 <code>brand</code> 的 <code>products<brand</code> 的 <code>products<brand</code> 的 <code>products<brand</code> 的 <code>products< </p> <pre class="brush:php;toolbar:false;">namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Str; class Brand extends Model { use HasFactory; /*** 該模型的附加屬性*/ protected $appends = [ 'prices' ]; protected $fillable = [ 'title' ]; /***“啟動”模型的方法。 * * @回傳無效*/ protected static function booted() { static::creating(function ($brand) { $brand->slug = Str::slug($brand->title, '-', 'de'); }); } /*** 回饋某個品牌的所有產品 * * @return 有很多*/ public function products(): HasMany { return $this->hasMany(Product::class); } }</pre> <h2>產品型號</h2> <p>每個<code>產品</code>都屬於一個<code>品牌</code>。附加屬性 <code>title_medium</code> 應連接品牌標題和產品標題。</p>
 命名空間 App\Models;

產品類別擴展模型
{
    使用 HasFactory、可搜尋、可過濾;

    受保護的$可填充= [
        '標題',
        '品牌 ID',
        '圖像'
    ];

    /*** 該模型的附加屬性*/
    受保護的 $appends = [
        '標題長',
        '最低價格',
        '最高折扣百分比價格',
        '最新價格日期',
        '價格計數'
    ];

    /***“啟動”模型的方法。
     *
     * @回傳無效*/
    受保護的靜態函數 booted()
    {
        靜態::建立(函數($產品){
            $product->slug = Str::slug($product->title_long, '-', 'de');
        });
    }

    /*** 產品屬於一個品牌*/
    公共功能品牌():BelongsTo
    {
        返回 $this->belongsTo(Brand::class);
    }

    /*** 取得產品和品牌的組合標題*/
    公用函數 getTitleMediumAttribute(): 字串
    {
        // 這會導致“可能的無限循環異常”在 xdebug 中
        返回 $this->brand->title 。 ''。 $這個->標題;
    }
}</pre></p>
P粉786432579P粉786432579381 天前396

全部回覆(1)我來回復

  • P粉306523969

    P粉3065239692023-09-05 15:17:18

    嘗試使用 屬性 而不是 < code>getTitleMediumAttribute,像這樣並告訴我是否仍然遇到相同的錯誤(使用此方法而不是 `getTitleMediumAttribute):

    public function titleMedium(): Attribute
    {
        return Attribute::get(
            fn () => "{$this->brand->title} $this->title",
        );
    }
    

    屬性\Illuminate\Database\Eloquent\Casts\Attribute

    #

    回覆
    0
  • 取消回覆