Laravel Eloquent 为属性添加前缀
Laravel Eloquent add a prefix to an attribute
我有一个 table,其中包含我所在国家/地区的地区名称。有没有一种简单易行的方法可以在每个名字前添加 'District' 字符串?
有我的table结构:
+------------------------+
| id | name |
+----+-------------------+
| 1 | Sofia |
+----+-------------------+
| 2 | Shumen |
+----+-------------------+
| 3 | Varna |
+------------------------+
我需要在调用 District::find(1)->name 时获取 'District Shumen'。
您可以为此创建一个 attribute accessor。在您的模型中:
public function getNameAttribute(){
return 'District ' . $this->attributes['name'];
}
我有一个 table,其中包含我所在国家/地区的地区名称。有没有一种简单易行的方法可以在每个名字前添加 'District' 字符串?
有我的table结构:
+------------------------+
| id | name |
+----+-------------------+
| 1 | Sofia |
+----+-------------------+
| 2 | Shumen |
+----+-------------------+
| 3 | Varna |
+------------------------+
我需要在调用 District::find(1)->name 时获取 'District Shumen'。
您可以为此创建一个 attribute accessor。在您的模型中:
public function getNameAttribute(){
return 'District ' . $this->attributes['name'];
}