将集合中的 created_at 值更改为 carbon 人类可读
Change created_at value in collection to be carbon human readable
我正在尝试输出集合 created_at 时间以供 JSON 请求的人类可读。
以下代码有效:
$childComments = $comment->getParentsChildren($comment->id , $childCount)->with('creator')->get();
return $childComments->map(function($childComments){
return [
'created_at' => $childComments->created_at->diffForHumans()
];
});
问题是只有 returns created_at,我想 return $childComments 集合的其余部分,而不必手动添加每个 属性。
我试过这个:
return $childComments->map(function($childComments){
$childComments->created_at = $childComments->created_at->diffForHumans();
});
并抛出此错误。
{message: "A two digit month could not be found↵Data missing", exception: "InvalidArgumentException",…}
exception
:
"InvalidArgumentException"
file
:
"/Applications/MAMP/htdocs/community/vendor/nesbot/carbon/src/Carbon/Carbon.php"
编辑访问器尝试:
控制器
return $childComments->each(function($childComments){
$childComments->created_at = $childComments->humanDate;
});
评论模型
public function getHumanDate()
{
return $this->created_at->diffForHumans();
}
我现在在 JSON 输出中的所有 created_at 日期都为空。
更正: Eloquent 将时间戳字段与 Carbon 对象相互转换。差异无法解析为新的 Carbon 对象。
一个简单的解决方案就是将此字段重命名为类似 created_diff
的名称,这样模型就不会尝试解析它。
您还需要 return 映射闭包中的对象,否则,集合将只填充空值:
return $childComments->map(function($childComments){
$childComments->created_diff = $childComments->created_at->diffForHumans();
return $childComments;
});
或者因为对象是可变的并且通过引用传递,你也可以只使用每个:
return $childComments->each(function($childComments){
$childComments->created_diff = $childComments->created_at->diffForHumans();
});
我正在尝试输出集合 created_at 时间以供 JSON 请求的人类可读。
以下代码有效:
$childComments = $comment->getParentsChildren($comment->id , $childCount)->with('creator')->get();
return $childComments->map(function($childComments){
return [
'created_at' => $childComments->created_at->diffForHumans()
];
});
问题是只有 returns created_at,我想 return $childComments 集合的其余部分,而不必手动添加每个 属性。
我试过这个:
return $childComments->map(function($childComments){
$childComments->created_at = $childComments->created_at->diffForHumans();
});
并抛出此错误。
{message: "A two digit month could not be found↵Data missing", exception: "InvalidArgumentException",…} exception : "InvalidArgumentException" file : "/Applications/MAMP/htdocs/community/vendor/nesbot/carbon/src/Carbon/Carbon.php"
编辑访问器尝试:
控制器
return $childComments->each(function($childComments){
$childComments->created_at = $childComments->humanDate;
});
评论模型
public function getHumanDate()
{
return $this->created_at->diffForHumans();
}
我现在在 JSON 输出中的所有 created_at 日期都为空。
更正: Eloquent 将时间戳字段与 Carbon 对象相互转换。差异无法解析为新的 Carbon 对象。
一个简单的解决方案就是将此字段重命名为类似 created_diff
的名称,这样模型就不会尝试解析它。
您还需要 return 映射闭包中的对象,否则,集合将只填充空值:
return $childComments->map(function($childComments){
$childComments->created_diff = $childComments->created_at->diffForHumans();
return $childComments;
});
或者因为对象是可变的并且通过引用传递,你也可以只使用每个:
return $childComments->each(function($childComments){
$childComments->created_diff = $childComments->created_at->diffForHumans();
});