Laravel Eloquent Serialization:如何重命名属性


Laravel Eloquent Serialization: how to rename property?

例如,我有用户模型扩展Eloquent。在数据库表中,列名为 user_id

读取后如何将结果输出为"userId"?

使用属性访问器添加单个"别名"

您可以使用属性访问器来创建"新属性":

public function getUserIdAttribute(){
    return $this->attributes['user_id'];
}

这允许您通过以下方式访问值:$user->userId

现在让我们将值添加到数组/JSON 转换中:

protected $appends = array('userId');

最后隐藏丑陋的user_id

protected $hidden = array('user_id');


转换为数组/JSON 时转换所有属性名称

您还可以使用 toArray() 在将模型转换为数组或 JSON 字符串时更改所有属性名称。

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(array_key_exists($key, $array)) {
            $array[$new_key] = $array[$key];
            unset($array[$key]);
        }
    }
    return $array;
}