Laravel Eloquent Serialization: how to rename property?(Laravel Eloquent Serialization:如何重命名属性?)
问题描述
例如,我有扩展 Eloquent 的用户模型.在数据库表中,列名是user_id
.
For example, I have User model extending Eloquent. In the database table, the column name is user_id
.
阅读后如何将结果输出为'userId'?
How do I output the result as 'userId' after reading?
推荐答案
使用属性访问器添加单个别名"
您可以使用属性访问器来创建新属性":
public function getUserIdAttribute(){
return $this->attributes['user_id'];
}
这允许您以这种方式访问值:$user->userId
This allows you to access the value this way: $user->userId
现在让我们将值添加到数组/JSON 转换中:
Now let's add the value to array / JSON conversion:
protected $appends = array('userId');
最后隐藏丑陋的user_id
:
protected $hidden = array('user_id');
在将模型转换为数组或 JSON 字符串时,您还可以使用 toArray()
更改所有属性名称.
You can also use toArray()
to change the all attribute names when converting the model into an array or JSON string.
public function toArray(){
$array = parent::toArray();
$camelArray = array();
foreach($array as $name => $value){
$camelArray[camel_case($name)] = $value;
}
return $camelArray;
}
这篇关于Laravel Eloquent Serialization:如何重命名属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel Eloquent Serialization:如何重命名属性?


- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01