2016-10-06 183 views
2

我在数据库中有3个不同的字段:city,state,country。如何在Eloquent中定义另一个属性以从这3个字段返回一个字符串?在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