只要您愿意使用与“end_time”不同的名称,您提供的链接就应该是您的解决方案。您可以附加“end_time_formatted”或类似的内容。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
protected $appends = ['end_time_formatted'];
public function getEndTimeFormattedAttribute()
{
return $this->end_time->toAtomString();
}
}
然后,每当您将模型转换为 json 时,它都会包含“end_time_formatted”。
您的另一个选择(如果您需要保持相同的名称)是通过将 toJson 方法复制到您的模型中来覆盖它。我可能会建议不要这样做,但它会避免$this->created_at = $this->created_at->toAtomString()
每次在将其转换为 JSON 之前都需要说明。
/**
* Convert the model instance to JSON.
*
* @param int $options
* @return string
*
* @throws \Illuminate\Database\Eloquent\JsonEncodingException
*/
public function toJson($options = 0)
{
$atom = $this->created_at->toAtomString();
$json = json_encode($this->jsonSerialize(), $options);
if (JSON_ERROR_NONE !== json_last_error()) {
throw JsonEncodingException::forModel($this, json_last_error_msg());
}
$json = json_decode($json);
$json->created_at = $atom;
$json = json_encode($json);
return $json;
}
我无法通过更改方法顶部的值来使其工作,所以我被迫 json_decode,然后重新编码,这对我来说感觉不太好。如果您确实使用这条路线,我建议您深入挖掘以尝试使其工作而无需解码。