在Eloquent中定义自定义属性

3

我在数据库中有三个不同的字段:citystatecountry。如何在Eloquent中定义另一个属性,以从这些3个字段返回一个字符串?

第一种方法,但它不起作用:

protected $address = "";

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

10
如果您想要一个模型中没有定义的新属性,您需要将该属性附加到您的模型中。
/**
 * 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

这是针对已映射到数据库表的属性。但是,当我调用$this->address时,它不返回任何内容。 - ln9187

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接