2016-10-06 10 views
2

私はデータベースに3種類のフィールド、city,statecountryを持っています。どのように私は3つのフィールドから1つの文字列を返すEloquentの別の属性を定義するのですか?Eloquentでカスタム属性を定義する

最初のアプローチが、それは動作しません:

protected $address = ""; 

public function getAddress() : string { 
    return $this->city . $this->state . " - " . $this->country; 
} 

答えて

9

をあなたは新しい属性をしたい場合モデルに定義されていない場合は、その属性をモデルに追加する必要があります。

/** 
* The accessors to append to the model's array form. 
* 
* @var array 
*/ 
protected $appends = ['address']; 

そして、あなたの属性メソッド定義:

/** 
* Get the address. 
* 
* @return string 
*/ 
public function getAddressAttribute() 
{ 
    return $this->city . $this->state . " - " . $this->country; 
} 
+0

これは動作します!!!!!!! – ln9187

0

はそれを動作させるために、メソッド名にAttributeを追加します。

public function getAddressAttribute() 
{ 
    return $this->city.$this->state.' - '.$this->country; 
} 

https://laravel.com/docs/5.3/eloquent-mutators#defining-an-accessor

+0

すでにしかし、データベーステーブルにマップされた属性のためです。 '$ this-> address'を呼び出すと何も返されない – ln9187

関連する問題