2016-04-28 24 views

回答

1

你可以試試這個(使用訪問):

型號

public function getIdAttribute() { 
     return $this->attributes['_id']; 
} 

控制器檢測

$user = User::find(1); 
// this will call getIdAttribute which will return the `_id` 
dd($user->id); 

您還可以覆蓋指定者()方法,如果你想展示它:

型號

// .. 
// getIdAttribute() 
// .. 
public function toArray() 
{ 
    $array = parent::toArray(); 
    $array['id'] = $this->id; 
    unset($array['_id']); 
    return $array; 
} 

控制器測試

$user = User::find(1); 
dd($user->toArray()); 
1

另一種方式來做到這一點是使用變壓器(http://fractal.thephpleague.com/transformers/)。這裏有一家Laravel的服務提供商(https://github.com/gathercontent/laravel-fractal)。 它會做,在一個優雅的方式:)

當然,如果你只需要使用「ID」字段做,我會不喜歡zorx說:

public function getIdAttribute() { return $this->attributes['_id']; }

但你」可能會把它放在一些BaseModel或者abstractModel類中,這是你模型需要的父類。