Laravel 5.2 Eloquent toArray将属性设置为0

时间:2016-05-04 18:47:07

标签: php laravel eloquent

我有一个付款对象,从数据库中读取并调用 dd($ payment)

时看起来像这样
(defrule learn-about-120?
   (or (credit-value-bsc-first-result ?n)
       (credit-value-bsc-second-result ?n))
   (test (<= ?n  20))
   =>
   (bind ?reply (get-text-from-user  "Reponse here)"))
   (assert (learn-about-120-response ?reply )))

然而,当它调用toArray()时,它看起来像这样

#attributes: array:7 [▼
"user_id" => 90
"plan_id" => 4
"payment_id" => "AP-4AF14082B16992740"
"status" => "done"
"progress" => 0
"created_at" => "2016-05-04 18:05:48"
"updated_at" => "2016-05-04 18:06:21"
]

任何想法为什么?

查询:

array:7 [▼
  "user_id" => 90
  "plan_id" => 4
  "payment_id" => 0
  "status" => "done"
  "progress" => 0
  "created_at" => "2016-05-04 18:05:48"
"updated_at" => "2016-05-04 18:06:21"
]

1 个答案:

答案 0 :(得分:1)

这可能是因为三种可能性之一(均在Payment模型中):

1

有一个Accessor集看起来像:

public function getPaymentIdAttribute($value) {
    return (int)$value;
}

2

您在模型中设置了$casts字段,如下所示:

protected $casts = [
    ...
    'payment_id' => 'integer',
    ...
];

如果您正在调用$attributes数组,这两件事就不会吃午饭。

修改

3

这是你的答案:

因为如果payment_id是模型中的主键 - 那么laravel模型会在toArray()调用时自动将其转换为int。对此的解决方案是在Payment模型中将它(它将覆盖Laravel默认值)转换为这样的字符串:

protected $casts = [
    ...
    'payment_id' => 'string',
    ...
];