【问题标题】:How do I add a custom field to a eloquent model in Laravel?如何在 Laravel 的 eloquent 模型中添加自定义字段?
【发布时间】:2016-12-22 17:24:48
【问题描述】:

我需要在加载时向 eloquent 模型添加自定义字段。处理结果收集时,带有附加的方法不起作用

protected $appends = ['formatted_date'];
public function getFormattedDateAttribute()
{
    return $this->date->format('D-m-y');
}

当我尝试 $collection->pluck($key, 'formatted_date') 时,出现错误 ** Unknown column 'formatted_date' in 'field list'**

【问题讨论】:

  • 已解决,问题是要收集的源数据,如果使用 $collection = Table::whereBetween('date',[$from, $to]) ,只需添加 get() 即可

标签: laravel eloquent laravel-5.2


【解决方案1】:

你试过了吗?

 $collection->toArray();
 $collection->toJson();

【讨论】:

    【解决方案2】:

    问题解决了,这会导致错误

    $collection = Table::whereBetween(‌​'date',[$from, $to]);
    $result = $collection->pluck($key, 'formatted_date');
    

    这是正确的:

    $collection = Table::whereBetween(‌​'date',[$from, $to])->get();
    $result = $collection->pluck($key, 'formatted_date');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2013-06-18
      • 1970-01-01
      • 2015-09-23
      • 2018-09-13
      • 1970-01-01
      • 2019-01-28
      相关资源
      最近更新 更多