【问题标题】:Laravel append attribute giving out of memory errorsLaravel 附加属性给出内存不足错误
【发布时间】:2018-08-26 16:35:56
【问题描述】:

我正在尝试将产品价格属性附加到产品型号,但当我打印它时它最终会出现内存不足错误。 当我在响应中执行dd 时,它给了我一些查询生成器错误。 谁能帮帮我?

我的数据库和模型如下:

我有三张桌子productsproduct_priceweight_units。 在[![product_price][1]][1] 表中,我有product_id , price, weight, weight_unit_id,在weight_units 中,我有unit

我的 product_price 模型

 public function weightUnit()
    {
        return $this->belongsTo('App\Models\WeightUnit');
    }

我的产品型号

protected $appends = ['product_price'];

 public function price(){
       return $this->hasMany(ProductPrice::class);
    }
 public function getProductPriceAttribute(){
        return $this->price()->with('weightUnit:id,unit');
    }

我的控制器

$data=   Product::take(2)->get();
        echo '<pre>';
        dd($data->toArray());

当我尝试打印时,它会出现内存不足错误,当我执行 dd 时,我会看到屏幕截图中的内容。

【问题讨论】:

  • productPrice 属性为您提供了一个查询生成器实例。你不想要一个字符串/整数吗?
  • @Marwelln 是的,我只想要这个值,但我不确定它为什么给我查询构建器实例。这假设不会发生

标签: laravel laravel-5 laravel-4 eloquent laravel-5.3


【解决方案1】:

$this-&gt;price() 只为您提供查询构建器实例,将其替换为 $this-&gt;price
然后将-&gt;with(替换为-&gt;load(

return $this->price->load('weightUnit:id,unit');

急切加载在那里没有多大意义,您应该将其移至price()

return $this->hasMany(ProductPrice::class)->with('weightUnit:id,unit');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多