我在数据库中有三个不同的字段:city
、state
、country
。如何在Eloquent中定义另一个属性,以从这些3个字段返回一个字符串?
第一种方法,但它不起作用:
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