使用 Eloquent 模型时,有时您只需要核心数据库属性,而不需要关系或计算属性。Laravel 的 attributeToArray 方法提供了一种简洁的方式来访问此原始模型数据。
// 基本用法$用户
=
用户
::
第一的
();$属性
=
$用户
->
属性到数组
();// Returns raw database attributes// ['id' => 1, 'name' => 'John', 'email' => 'john@example.com']
让我们探索一个实现模型变更审计系统的实际例子:
命名空间
应用程序\模型
;使用
App\Models\AuditLog
;使用
照亮\数据库\雄辩\模型
;班级
AuditableModel
延伸
模型{
受保护
静止的
功能
已启动
(){
静止的::
更新
(
功能
($model) {$original
=
$模型
->
获取原始
();$当前
=
$模型
->
属性到数组
();
// Compare only actual database attributes$changes
=
数组差异
($current, $original);
如果
(
!
空的
($changes)) {
AuditLog
::
创造
([
'model_type'
=>
获取类
($model),
'model_id'
=>
$模型
->
ID,
'原来的'
=>
json_encode
($original),
'changes'
=>
json_encode
($changes),
'用户身份'
=>
授權
()
->
ID
(),
时间戳
=>
现在
()]);}});}}班级
产品
延伸
AuditableModel{
受保护
$appends
=
[
'formatted_price'
,
'stock_status'
];
民众
功能
类别
(){
返回
$this
->
属于
(
类别
::班级
(英文):}
民众
功能
getFormattedPriceAttribute
(){
返回
"$"
。
数字格式
(
$this
->
价格
/
100
,
2
(英文):}}
attributesToArray 方法提供对存储在数据库中的模型属性的直接访问,这使其非常适合需要原始数据而不需要额外的计算属性或关系的场景。







