Laravel在__constructor中为模型添加属性

时间:2016-02-12 12:00:17

标签: laravel

我试图在我的模型中添加一个属性,所以我可以说:$model->path,然后返回一个网址。所以我已经将以下内容添加到模型的构造函数中:

public function __construct($attributes = array()){

    $this->path = url('img/' . $this->{'file-name'});
    parent::__construct($attributes);

}

但如果我运行Model::first(),我会得到以下内容:

{
  id: 25,
  text: "A lovely file",
  file-name: "file.jpg",
  created_at: "2016-02-12 11:44:37",
  updated_at: "2016-02-12 11:44:37"
},

您会注意到没有path属性。我做错了什么?!我想看看:

{
  id: 25,
  text: "A lovely file",
  file-name: "file.jpg",
  path: "http://myapp.app:8000/img/file.jpg",
  created_at: "2016-02-12 11:44:37",
  updated_at: "2016-02-12 11:44:37"
},

为了记录,我还尝试了$this->field = 'value';,但也没有创建属性。

1 个答案:

答案 0 :(得分:3)

阅读documentation。你最好使用accessor method

public function getPathAttribute()
{
    return url('img/'.$this->file_name);
}

您也不应该在列/属性名称中使用破折号,对分隔符使用下划线约定。