本文介绍了在口才中定义自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 3 different fields in the database: city, state, country. How do I define another attribute in Eloquent to return one string from those 3 fields?

第一种方法,但无效:

protected $address = "";

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

推荐答案

如果您想要模型中未定义的新属性,则需要将该属性附加到模型中.

If you want a new attribute which is not defined in model, you need to append that attribute to your model.

/**
 * 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;
}

这篇关于在口才中定义自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 19:57
查看更多