我有一个包含 country_code
和 country_name
的表。
我的数据库中的每个用户的帐户上都有国家/地区代码。我想要做的是自动返回该用户的国家/地区名称而不是国家/地区代码。
我在我的用户模型中设置了一个访问器,但它似乎不起作用。
public function getCountryCodeAttribute($value): string
{
return Country::firstWhere('country_code', $value)->get('country_name');
}
它仍然返回country_code
任何帮助都会很棒
最佳答案
您正在使用返回模型的 QueryBuilder()。要访问模型上的属性,只需像属性一样访问它即可。
return Country::firstWhere('country_code', $value)->country_name;
要为您的端点公开它,请使用用户模型追加属性,您可以在其中将自定义 Eloquent Setter 添加到序列化中。
class User {
protected $appends = [
'country_code',
];
}
关于php - Laravel 使用访问器从国家/地区代码返回国家/地区名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59888661/