我在數據庫中有3個不同的字段:city
,state
,country
。如何在Eloquent中定義另一個屬性以從這3個字段返回一個字符串?在Eloquent中定義自定義屬性
第一種方法,但它不工作:
protected $address = "";
public function getAddress() : string {
return $this->city . $this->state . " - " . $this->country;
}
我在數據庫中有3個不同的字段:city
,state
,country
。如何在Eloquent中定義另一個屬性以從這3個字段返回一個字符串?在Eloquent中定義自定義屬性
第一種方法,但它不工作:
protected $address = "";
public function getAddress() : string {
return $this->city . $this->state . " - " . $this->country;
}
如果你想有一個新的屬性這在模型中沒有定義,您需要將該屬性追加到模型中。
/**
* 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;
}
添加Attribute
方法名,使其工作:
public function getAddressAttribute()
{
return $this->city.$this->state.' - '.$this->country;
}
https://laravel.com/docs/5.3/eloquent-mutators#defining-an-accessor
這對於已經映射到數據庫表的屬性,雖然。當我調用'$ this-> address'時,它什麼也不返回。 – ln9187
它可以工作!!!!!!! – ln9187