Laravel Eloquent(不会显示Model属性)

时间:2019-04-01 18:52:56

标签: laravel eloquent attributes undefined

我有一个Stat班级:

class Stat extends Model
{
    public static function getByKey($key)
    {
        return Stat::where("key", "=", $key)->first();
    }

    public function getDates()
    {
        return json_decode($this->content);
    }
}

在我的数据库中,表stats仅包含两列(键,内容) 当我在视图中执行此功能时,会发生错误

{!! \App\Stat::getByKey("ORDERS-DATA")->getDates() !!}

这将导致此错误:

Exception message: Undefined property: App\Stat::$content

因此我将这两行添加到getDates()中以调试错误:

public function getDates()
{
    dd($this->content);//This shows the same error
    dd($this->attributes["content"]);//This works fine and show me what I want
    return json_decode($this->content);
}

然后我执行了dd($this),它显示了这一点:

Stat {#486
  #connection: "mysql"
  #table: "stats"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:5 [
    "id" => 8
    "key" => "ORDERS-DATA"
    "content" => """
      [
      {
      \t"day": "2019-04-01",
      \t"count": "5"
      }
      ]
      """
    "created_at" => "2019-04-01 14:09:00"
    "updated_at" => "2019-04-01 14:11:02"
  ]
  #original: array:5 [
    "id" => 8
    "key" => "ORDERS-DATA"
    "content" => """
      [
      {
      \t"day": "2019-04-01",
      \t"count": "5"
      }
      ]
      """
    "created_at" => "2019-04-01 14:09:00"
    "updated_at" => "2019-04-01 14:11:02"
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [
    0 => "*"
  ]
}

我想要的是将content换成$this->content,我不明白为什么它不起作用? 请帮助

1 个答案:

答案 0 :(得分:0)

发生错误是因为我已重写Laravel函数之一。 Laravel使用名称getDatesgetByKeygetCounts

  

这太奇怪了,这个错误在同一时间两次发生在我身上   那天早上,我创建了一个名为getAttributes()的函数,   向我展示了一个完全不同的错误。为什么社区不创造一个   我们不允许使用的函数名称列表,或更多   唯一名称???