Laravel Eloquent Serialization:如何重命名属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27867569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:40:03  来源:igfitidea点击:

Laravel Eloquent Serialization: how to rename property?

phplaraveleloquent

提问by DrXCheng

For example, I have User model extending Eloquent. In the database table, the column name is user_id.

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

How do I output the result as 'userId' after reading?

阅读后如何将结果输出为“userId”?

回答by lukasgeiter

Add single "aliases" using attribute accessors

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

You can use attribute accessorsto create "new attributes":

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

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

This allows you to access the value this way: $user->userId

这允许您以这种方式访问​​该值: $user->userId

Now let's add the value to array / JSON conversion:

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

protected $appends = array('userId');

And finally hide the ugly user_id:

最后隐藏丑陋user_id

protected $hidden = array('user_id');



Convert all attribute names when converting to array / JSON

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

You can also use toArray()to change the all attribute names when converting the model into an array or JSON string.

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

public function toArray(){
    $array = parent::toArray();
    $camelArray = array();
    foreach($array as $name => $value){
        $camelArray[camel_case($name)] = $value;
    }
    return $camelArray;
}

回答by melson.jao

I do it in this way.

我是这样做的。

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;
}