我在数据库中有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