2016-02-12 52 views
1

我试图给我的模型添加一个属性,所以我可以这样说:$model->path然后找回一个url。所以,我添加了以下到模型的构造:Laravel将属性添加到__constructor中的模型

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';,并且没有可以创建一个属性。

回答

3

阅读documentation。你最好用accessor method

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

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

+0

如果模型或表上不存在'path'属性,则还需要'$ appends'属性。隐藏在:https://laravel.com/docs/5.1/eloquent-serialization#appending-values-to-json – Mysteryos

+0

这很好,谢谢 - 并在连字符上注明。有什么办法可以自动包含这个属性,或者我最好是做一些像''imgs = \ App \ Img :: all(); foreach($ imgs as $ img){$ img-> url = $ img-> path;' - 就这样我的API返回的集合格式化得很好? – Djave

+0

@Djave As @Mysteryos说,你可以在你的'$ appends'数组中添加'path',这将包含任何序列化为JSON,数组等的值。 –