【问题标题】:laravel Model returns null on calling another function from same modellaravel 模型在从同一模型调用另一个函数时返回 null
【发布时间】:2020-08-02 18:07:09
【问题描述】:

我有一个产品模型,其中有一个attribute function,它返回某些数据。

通常如果我用Product::with(['attributes'])->active()->paginate(config('app.rec_limit')); 调用它,我会得到输出。

但如果我这样做,我将无法访问模型中的该数据或任何其他 function 数据,

    protected $appends = ['product_attributes'];

    public function getProductAttributesAttribute() {
        return $this->attributes();
    }

    public function attributes() {
        return $this->hasMany(ProductAttribute::class);
    }

如果我在getProductAttributesAttribute function 中传递一个字符串,我会得到该字符串作为输出。

这里输出一个空数组的原因是什么?

【问题讨论】:

  • 不需要使用accessor,可以通过with方法获取属性。如果要使用访问器,则需要在getProductAttributesAttribute 中返回$this->attributes;,但我不建议这样做。因为每次调用 Product 时,它都会进行预先加载。
  • 你可以试试这个 return $this->attributes()->get();

标签: arrays laravel function eloquent model


【解决方案1】:

修改你的代码:return $this->attributes(); 返回一个雄辩的对象,而不是一个集合,就好像你还想执行其他查询一样。更改为return $this->attributes;,它返回一个集合

请注意,使用这意味着为每个产品模型获取属性,这可能会导致以后出现性能问题。

理想的方式是将其保留为模型关系,然后仅在需要时调用它

【讨论】:

    猜你喜欢
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多