【问题标题】:Laravel - add a class attribute to arrayLaravel - 向数组添加类属性
【发布时间】:2021-02-11 21:14:33
【问题描述】:

在我的 Eloquent 模型中,我添加了一个类属性:

/**
 * @return bool
 */
public function getIsViewable()
{
    return $this->isViewable;
}

这个属性没有保存在数据库中,因为它只是一个计算值。

在我的控制器中,我有一个此对象的 Eloquent 集合,我将其转换为数组:

$images = $query->get();
$images = $images->toArray();

如何将类属性属性添加到数组中的每个图像项?

【问题讨论】:

标签: laravel eloquent


【解决方案1】:
  1. 方法应该命名为getMyVariableAttribute,即。 getIsViewableAttribute
  2. 在模型上添加以下protected $appends = ['is_viewable'],以便在序列化时获取计算属性。

【讨论】:

    【解决方案2】:

    您的方法名称缺少Attribute 部分。将getIsViewable() 重命名为getIsViewableAttribute()

    /**
     * @return bool
     */
    public function getIsViewableAttribute()
    {
        return $this->isViewable;
    }
    

    https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-09
      • 1970-01-01
      • 2018-02-25
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      相关资源
      最近更新 更多