例如,我有用户模型扩展Eloquent . 在数据库表中,列名是 user_id .
user_id
如何在阅读后将结果输出为'userId'?
您可以使用attribute accessors创建"new attributes":
public function getUserIdAttribute(){ return $this->attributes['user_id']; }
这允许您以这种方式访问值: $user->userId
$user->userId
现在让我们将值添加到array / JSON转换:
protected $appends = array('userId');
最后隐藏丑陋的 user_id :
protected $hidden = array('user_id');
在将模型转换为数组或JSON字符串时,您还可以使用 toArray() 更改所有属性名称 .
toArray()
public function toArray(){ $array = parent::toArray(); $camelArray = array(); foreach($array as $name => $value){ $camelArray[camel_case($name)] = $value; } return $camelArray; }
我是这样做的 .
protected $remap_attrs = ['old_name' => 'new_name']; public function toArray(){ $array = parent::toArray(); foreach($this->remap_attrs as $key => $new_key) { if(isset($array[$key])) { $array[$new_key] = $array[$key]; unset($array[$key]); } } return $array; }
2 回答
使用属性访问器添加单个“别名”
您可以使用attribute accessors创建"new attributes":
这允许您以这种方式访问值:
$user->userId
现在让我们将值添加到array / JSON转换:
最后隐藏丑陋的
user_id
:转换为array / JSON时转换所有属性名称
在将模型转换为数组或JSON字符串时,您还可以使用
toArray()
更改所有属性名称 .我是这样做的 .