2016-10-11 143 views
3

下面是模型的代碼

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Product extends Model 
{ 
    protected $appends = [ 
     "desc" 
    ]; 

    protected $fillable = ['id']; 

    public function getDescAttribute() 
    { 
     return strip_tags($this->attributes['description']); 
    } 
} 

所以,現在當我這樣做

$product = Product::first(); 

它不會在$產品退回遞減領域,雖然當我這樣做$ product-> desc它返回結果,但我希望結果被附加在模型本身。

下面的代碼給我錯誤

$product = Product::first()->get(['desc']); 

它運行

Select desc from products... 

但由於遞減是不是有我收到錯誤。

我做錯了什麼?

+0

當你添加'protected $ visible = ['desc'];'? – Neat

+0

then'$ product = Product :: first();'顯示'App \ Product {#729}'不包含修改器中的列 – crazy1337

回答

1

添加到$的附加字段數組僅在對象爲時序列化爲數組/ JSON時附加。否則,直到真正需要時才定義此屬性是沒有意義的 - 這就是爲什麼當您訪問$ product-> desc時獲取該值的原因。這樣做是爲了節省不必要的操作 - 計算自定義屬性的值可能涉及一些繁重的操作,並延遲到真正需要時爲止。