例如,我有扩展 Eloquent 的用户模型。在数据库表中,列名是user_id
。
读取后如何将结果输出为'userId'?
最佳答案
使用属性访问器添加单个“别名”
您可以使用 attribute accessors创建“新属性”:
public function getUserIdAttribute(){
return $this->attributes['user_id'];
}
这允许您以这种方式访问值:$user->userId
现在让我们将值添加到数组/JSON 转换:
protected $appends = array('userId');
最后隐藏丑陋的user_id
:
protected $hidden = array('user_id');
转换为数组/JSON时转换所有属性名
在将模型转换为数组或 JSON 字符串时,您还可以使用 toArray()
更改所有属性名称。
public function toArray(){
$array = parent::toArray();
$camelArray = array();
foreach($array as $name => $value){
$camelArray[camel_case($name)] = $value;
}
return $camelArray;
}
关于php - Laravel Eloquent 序列化 : how to rename property?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27867569/